﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;
using ProgNetComponentsDx.Options;
using ProgNetComponentsDx.Browsers;
using System.Data;
using ProgNetComponents.Data.SqlCe;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text.RegularExpressions;
using DevExpress.XtraGrid.Views.Grid;
using System.Drawing;
using DevExpress.XtraGrid;
using System.Threading.Tasks;
using System.Windows.Automation;
using BuildHelper.Scheduler;
using ProgNetComponentsDx.Components;

namespace BuildHelper
{
    public static class GlobalTools
    {
        public static class Options
        {
            public static string CRPrefix
            {
                get
                {
                    return OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Commit.CRPrefix);
                }
            }
        }
        public static class Messages
        {
            public const string MSG_ERROR = "BH ERROR: ";
            public const string MSG_WARNING = "BH WARNING: ";
            public const string MSG_INFO = "BH INFO: ";
            public static bool HandleGlobalMsg(string str)
            {
                bool result = false;
                if (str.XMatch("^" + GlobalTools.Messages.MSG_INFO))
                {
                    FormMain.ShowInfoAlert(str.XReplace(GlobalTools.Messages.MSG_INFO, ""));
                    result = true;
                }
                if (str.XMatch("^" + GlobalTools.Messages.MSG_ERROR))
                {
                    FormMain.ShowErrorAlert(str.XReplace(GlobalTools.Messages.MSG_ERROR, ""));
                    result = true;
                }
                if (str.XMatch("^" + GlobalTools.Messages.MSG_WARNING))
                {
                    FormMain.ShowWarningAlert(str.XReplace(GlobalTools.Messages.MSG_WARNING, ""));
                    result = true;
                }
                return result;
            }
        }

        public static string GetOptionPath(object opt)
        {
            return Setup.Opcje.FormOpcje.GetOptionPath(opt);
        }
        private static string[] _Systems = null;
        private static string[] _JavaSystems = null;
        private static string[] _GuiSystems = null;

        public static string[] Systems
        {
            get
            {
                if (_Systems == null)
                {
                    DataTable dt = BrowserCache.GetBrowserData(Init.InitFormBrowserNames.Setup.Apps);
                    List<string> list = new List<string>();
                    foreach (DataRow r in dt.Rows)
                    {
                        list.Add(r["STP_APP_KOD"].AsString());
                    }
                    _Systems = list.ToArray();
                }
                return _Systems;
            }
        }
       
        public static string[] JavaSystems
        {
            get
            {
                if (_JavaSystems == null)
                {
                    DataTable dt = BrowserCache.GetBrowserData(Init.InitFormBrowserNames.Setup.Apps).SelectToTable("STP_APP_IS_JAVA = 1");
                    List<string> list = new List<string>();
                    foreach (DataRow r in dt.Rows)
                    {
                        list.Add(r["STP_APP_KOD"].AsString());
                    }
                    _JavaSystems = list.ToArray();
                }
                return _JavaSystems;
            }
        }
        public static string[] GuiSystems
        {
            get
            {
                if (_GuiSystems == null)
                {
                    DataTable dt = BrowserCache.GetBrowserData(Init.InitFormBrowserNames.Setup.Apps).SelectToTable("STP_APP_IS_GUI = 1");
                    List<string> list = new List<string>();
                    foreach (DataRow r in dt.Rows)
                    {
                        list.Add(r["STP_APP_KOD"].AsString());
                    }
                    _GuiSystems = list.ToArray();
                }
                return _GuiSystems;
            }
        }

        public static void RefreshSystems()
        {
            _Systems = null;
            _JavaSystems = null;
            _GuiSystems = null;
        }

        private static ExtendedWebClient _DefaultWebClient = null;
        public static ExtendedWebClient DefaultWebClient
        {
            get
            {
                if (_DefaultWebClient == null)
                    _DefaultWebClient = GetWebClient();
                return _DefaultWebClient;
            }
        }

        private static ExtendedWebClient _ShortTimeoutWebClient = null;
        public static ExtendedWebClient ShortTimeoutWebClient
        {
            get
            {
                if (_ShortTimeoutWebClient == null)
                {
                    _ShortTimeoutWebClient = GetWebClient();
                    _ShortTimeoutWebClient.Timeout = 4000;
                }
                return _ShortTimeoutWebClient;
            }
        }

        public static ExtendedWebClient GetWebClient()
        {
            ExtendedWebClient w = new ExtendedWebClient();
            if (w.Proxy != null)
            {
                w.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                w.Credentials = CredentialCache.DefaultNetworkCredentials;
                w.UseDefaultCredentials = true;
            }
            return w;
        }
        public static string GetFullPath(string path, string rootPath, string rootName = "%ROOT%")
        {
            string result = path;
            if (path.XMatch("^" + rootName.XEscape()))
            {
                result = path.XReplace("^" + rootName.XEscape(), "");
                result = result.TrimStart('\\');
                result = rootPath.TrimEnd('\\') + "\\" + result;
            }
            return result;
        }
        public static string GetBranczPath(string path, string rootName = "%ROOT%")
        {
            string result = path;
            if (path.XMatch("\\\\nd_src\\\\gene\\\\apps\\\\"))
            {
                result = path.XReplace(".*?\\\\nd_src\\\\gene\\\\apps\\\\", rootName+"\\gene\\apps\\");
            }
            return result;
        }
        public static SqlCeDataManager CreateManager()
        {
            SqlCeDataManager m = new SqlCeDataManager();
            m.AutoLogExceptions = true;
            return m;
        }

        #region Wybrane formy
        public static class WybraneFormy
        {
            public const string Srodowiska = "SR";
            public const string BazyDanych = "BD";
            public const string BudowanieGui = "B_GUI";
            public const string BudowanieJavy = "B_JAVA";
            public const string TortoiseSvn = "SVN";
            public const string OperacjeNaPlikach = "ONP";
            public const string Generator = "GEN";
        }
        #endregion
        #region TortoiseTools
        public static class TortoiseTools
        {
            private const string MSG_CHECK_OUT_DONE = "CheckOut zakończony";
            private const string MSG_UPDATE_DONE = "Update zakończony";
            private const string MSG_CLEANUP_DONE = "Cleanup zakończony";
            private const string MSG_NAPRAWIANIE_DONE = "Naprawianie zakończone";
            private const string MSG_CANCEL = "Operacja anulowana.";

            #region Getting info from window
           
            [DllImport("user32.dll", SetLastError = true)]
            public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
            public static void TryAddLogAfterCommit(Process tortoiseProc, string path)
            {
                Thread t = new Thread(new ParameterizedThreadStart(_TryAddLogAfterCommit));
                t.Start(new object[] { tortoiseProc, path });
            }
            private static Dictionary<Process, string> logs = new Dictionary<Process, string>();
            private static Dictionary<Process, bool> logsAdd = new Dictionary<Process, bool>();

            private static Dictionary<Process, KeyValuePair<string, string>> logRevisions = new Dictionary<Process, KeyValuePair<string, string>>();

            private static void _TryAddLogAfterCommit(object o)
            {
                object [] tab = o as object[];

                Process p = tab[0] as Process;
                string path = tab[1] as string;

                TortoiseProcWindow w = new TortoiseProcWindow(p);
                try
                {
                    while (w.Revision.IsNullOrEmpty() && !p.HasExited)
                    {
                        w.GetRev();
                        System.Threading.Thread.Sleep(10);
                    }
                    if (w.Revision.IsNotNull())
                    {
                        CreateLog(path, w.Revision, true);
                    }
                }
                catch (Exception ex)
                {
                    ex.LogError();
                }
            }
            private static void CreateLog(string path, string rev, bool retry)
            {
                System.Threading.Thread.Sleep(500);

                Process procLogi = GlobalTools.CreateCMDProcess(procLogi_Data);
                if (retry)
                    logRevisions.Add(procLogi, new KeyValuePair<string, string>(rev, path));
                
                logs.Add(procLogi, "");
                logsAdd.Add(procLogi, false);
                string cmd = "svn log " + path + " -r " + rev + " --incremental --verbose ";
                procLogi.EchoOff();
                GlobalTools.TortoiseTools.AddSvnToPath(procLogi);
                
                procLogi.Execute(cmd);
                procLogi.Echo("exit");
            }
            private static bool AddLogi(string log)
            {
                string logFile = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Logi.LogFile);
                if (logFile.IsNullOrEmpty())
                {
                    return false;
                }
                log = log + Constants.NewLineLinux;
                log.AppendToFile(logFile);
                return true;
            }
            private static void procLogi_Data(object sender, DataReceivedEventArgs e)
            {
                string msg = e.Data.AsString();
                Process p = sender as Process;
                if (!logsAdd.ContainsKey(p))
                    return;

                if (msg.XMatch("^echo exit"))
                {
                    try
                    {
                         string log = logs[p];
                         if (log.XMatch("svn: E155037:")) // need cleanup?
                         {
                             if (logRevisions.ContainsKey(p))
                             {
                                 CreateLog(logRevisions[p].Value, logRevisions[p].Key, false);
                             }
                             else
                             {
                                 FormMain.ShowWarningAlert("Błąd tworzenia logów.");
                             }
                         }
                         else
                         {
                             if (logRevisions.ContainsKey(p))
                                 logRevisions.Remove(p);
                             bool clip = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty.KopiujLogDoSchowka);
                             bool zapisz = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty.ZapisujLog);

                             if (log.IsNotNull())
                             {
                                 if (clip)
                                     Clipboard.SetText(log);

                                 if (zapisz)
                                     zapisz = AddLogi(log);
                                 if (zapisz)
                                 {
                                     if (clip)
                                         FormMain.ShowInfoAlert("Log zapiszany w schowku i pliku.");
                                     else
                                         FormMain.ShowInfoAlert("Log zapiszany w pliku.");
                                 }
                                 else if (clip)
                                 {
                                     FormMain.ShowInfoAlert("Log zapiszany w schowku.");
                                 }
                             }
                         }

                        logs.Remove(p);
                        logsAdd.Remove(p);
                        p.KillProcessTree();
                        p.Dispose();
                    }
                    catch { }
                }
                else if (logsAdd[p])
                {
                    logs[p] = logs[p].AppendLine(msg);
                }
                else if (msg.XMatch("svn log"))
                {
                    logsAdd[p] = true;
                }
            }
            public class TortoiseProcWindow
            {
                private Process TortoiseProcProcess
                {
                    get;
                    set;
                }
                private IntPtr SysListView
                {
                    get;
                    set;
                }
                public string Revision
                {
                    get;
                    set;
                }
                public bool IsInConflict
                {
                    get;
                    private set;
                }
                public bool StatusSet
                {
                    get;
                    private set;
                }
                public TortoiseProcWindow(Process p)
                {
                    TortoiseProcProcess = p;
                }

                public void GetRev(bool isUpdate = false)
                {
                    try
                    {
                        try
                        {
                            TortoiseProcProcess.Refresh();
                        }
                        catch { }
                        SysListView = FindWindowEx(TortoiseProcProcess.MainWindowHandle, IntPtr.Zero, "SysListView32", null);

                        if (SysListView != IntPtr.Zero)
                        {
                            AutomationElement el = AutomationElement.FromHandle(SysListView);
                            object pat;
                            if (el.TryGetCurrentPattern(System.Windows.Automation.GridPattern.Pattern, out pat))
                            {
                                System.Windows.Automation.GridPattern pattern = pat as System.Windows.Automation.GridPattern;
                                if (pattern.Current.RowCount > 0)
                                {
                                    string completed = pattern.GetItem(pattern.Current.RowCount - 1, 0).Current.Name;
                                    if (completed.XMatch("Completed"))
                                    {
                                        string revision = pattern.GetItem(pattern.Current.RowCount - 1, 1).Current.Name.GetFirstMatch("At Revision:\\s*(\\d*)");
                                        Revision = revision;
                                    }
                                    else if (isUpdate && completed.XMatch("Warning!"))
                                    {
                                        completed = pattern.GetItem(pattern.Current.RowCount - 2, 0).Current.Name;
                                        if (completed.XMatch("Completed"))
                                        {
                                            string revision = pattern.GetItem(pattern.Current.RowCount - 2, 1).Current.Name.GetFirstMatch("At Revision:\\s*(\\d*)");
                                            Revision = revision;
                                            IsInConflict = true;
                                            StatusSet = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ex.LogInternal();
                    }
                }
                public void GetStatus()
                {
                    GetRev(true);
                    try
                    {
                        if (TortoiseProcProcess.HasExited)
                            return;
                        if (Revision.IsNotNull())
                        {
                            IntPtr first = FindWindowEx(TortoiseProcProcess.MainWindowHandle, IntPtr.Zero, "Static", null);
                            IntPtr second = FindWindowEx(TortoiseProcProcess.MainWindowHandle, first, "Static", null);
                            if (second != IntPtr.Zero)
                            {
                                string text = Win32.GetWindowText(second);
                                if (text.XMatch("Conflict"))
                                {
                                    IsInConflict = true;
                                }
                                StatusSet = true;
                            }
                        }
                    }
                    catch { }
                }
            }
            #endregion
            private class RunTortoiseInfo
            {
                public string Brancz
                {
                    get;
                    set;
                }
                public DataRow Row
                {
                    get;
                    set;
                }
            }
            private class CheckOutInfo
            {
                public FileBgAppender FielAppender { get; set; }
                public string File { get; set; }
                public Process Process { get; set; }
                public string brancz { get; set; }
                public int CurApp { get; set; }
                public int CurDir { get; set; }
                public int MaxDirs { get; set; }
                public int MaxApps { get; set; }
                public bool IsCheckOut { get; set; }
                public void KoniecOperacji(string message)
                {
                    if (Process != null)
                    {
                        if (message == MSG_CANCEL)
                            FormMain.ShowWarningAlert(message);
                        else
                            FormMain.ShowInfoAlert(message);

                        try
                        {
                            Process.KillProcessTree();
                            Process.Dispose();
                        }
                        catch { }
                        FielAppender.Finish();
                        FielAppender.Dispose();
                        Process.Start(File);
                        checkOutProc.Remove(Process);
                        Process = null;
                        FormMain.CloseAlertById("CHECK_OUT" + brancz);
                    }
                }
                public void SetProgress()
                {
                    string text = "Katalog: " + CurDir + "/" + MaxDirs + " ; App:" + CurApp + "/" + MaxApps;
                    FormMain.UpdateAlertText("CHECK_OUT" + brancz, "SVN CheckOut [" + brancz + "]" + Constants.NewLineLinux +
                        text.Replace(";", Constants.NewLineLinux));
                }
                public void PoczatekOperacji()
                {
                    File = GlobalTools.FilesTools.GetTemplLogFile("svn_" + (IsCheckOut ? "CheckOut_" : "Update_") + brancz);
                    FielAppender = new FileBgAppender();
                    FielAppender.FileName = File;
                    FielAppender.Start();
                }
            }

            private static Dictionary<Process, CheckOutInfo> checkOutProc = new Dictionary<Process, CheckOutInfo>();

            public static void TortoiseProcUpdate(string brancz, DataRow r)
            {
                if (brancz.IsNull())
                    brancz = Setup.Brancze.BranczeTools.ActiveBranch;
                if (brancz.IsNull())
                {
                    FormMain.ShowErrorAlertDontHide("TortoiseProc Update " + Constants.NewLineLinux + "Brak brancza!");
                    return;
                }
                if (r != null)
                {
                    RunTortoiseInfo i = new RunTortoiseInfo();
                    i.Brancz = brancz;
                    i.Row = r;
                    Thread t = new Thread(new ParameterizedThreadStart(_TortoiseProcUpdate));
                    t.Start(i);
                }
                else
                {
                    RunTortoise(brancz, "update");
                }
            }
            private static void _TortoiseProcUpdate(object arg)
            {
               RunTortoiseInfo a = arg as RunTortoiseInfo;
               Process p = RunTortoise(a.Brancz, "update");
               if (p != null)
               {
                   TortoiseProcWindow w = new TortoiseProcWindow(p);
                   while (!p.HasExited && !w.StatusSet)
                   {
                       w.GetStatus();
                       Thread.Sleep(50);
                   }
                   string status;

                   if (w.StatusSet)
                   {
                       if (w.IsInConflict)
                          status = Zadanie.Statusy.ZakonczoneZBledem;
                       else
                           status = Zadanie.Statusy.Zakonczone;
                   }
                   else
                   {
                      status = Zadanie.Statusy.Nieznany;
                   }
                   try
                   {
                       if (FormMain.Instance.InvokeRequired)
                       {
                           FormMain.Instance.Invoke(new Action(() =>
                           {
                               a.Row["STATUS"] = status;
                           }));
                       }
                       else
                       {
                           a.Row["STATUS"] = status;
                       }
                   }
                   catch (Exception ex) { ex.Log(); }
               }
            }

            public static void Commit(string brancz)
            {
                if (CanUseTortoiseProc())
                {
                    string command = "commit";
                    string msg = GlobalTools.TortoiseTools.GetLogMessage();
                    if (msg == null)
                        return;
                    if (msg.IsNotNull())
                        command += " /logmsg:" + msg.AddDoubleQuotes();
                    GlobalTools.TortoiseTools.RunTortoise(brancz, command, useApps: OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise.DirForCommit) == "A");
                }
                else
                {
                    FormMain.Instance.ShowDxErrorDialog("Nie znaleziono TortoiseProc.\nSprawdź opcje " + GlobalTools.GetOptionPath(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseProc));
                }
            }
            public static void SvnCheckOutUpdate(string brancz, bool checkOut)
            {
                BHTasks.CheckOutUpdateTask t = new BHTasks.CheckOutUpdateTask();
                t.IsCheckOut = checkOut;
                t.Brancz = brancz;
                t.Run();
            }

            public static Process RunTortoise(string brancz, string command, bool addUrl = false, bool useApps = false, string pathFile ="")
            {
                if (CheckTortoiseProc())
                {
                    if (brancz.IsNull())
                    {
                        FormMain.Instance.ShowDxInfoDialog("Wybierz brancza.");
                        return null;
                    }
                    string file = GetTortoiseProcPath();
                    DataRow br = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Brancze, brancz);
                    if (br != null)
                    {
                        string katalog = br["STP_BR_KATALOG"].AsString().TrimEnd('\\', '/');
                        string path = katalog + "\\nd_src\\gene";
                        if (useApps)
                            path = path + "\\apps";
                        path = path.AddDoubleQuotes();
                        return RunTortoiseGlobal(br["STP_BR_SVN"].AsString(), command, path, false, addUrl, pathFile);
                    }
                    else
                    {
                        FormMain.Instance.ShowDxErrorDialog("Nie można odnaleźć katalogu brancza");
                    }
                }
                return null;
            }
            public static bool CheckTortoiseProc(bool showInfo =true)
            {
                if (!CanUseTortoiseProc())
                {
                    if(showInfo)
                        FormMain.Instance.ShowDxErrorDialog("Nie znaleziono TortoiseProc.\nSprawdź opcje " + GlobalTools.GetOptionPath(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseProc));
                    return false;
                }
                return true;
            }

            public static Process RunTortoiseGlobal(string branczSvn, string command, string path= ".", bool urlAsPath = false, bool addUrl=false, string pathFile = "")
            {
                if (CheckTortoiseProc())
                {
                    if (branczSvn.IsNull())
                    {
                        FormMain.Instance.ShowDxInfoDialog("Wybierz brancza.");
                        return null;
                    }
                    string file = GetTortoiseProcPath();

                    if ((!path.StartsWith("\"") || !path.EndsWith("\"")) && path!=".")
                        path = path.AddDoubleQuotes();

                    string param = "";
                    string paramUrl = "";
                    if (addUrl || urlAsPath)
                    {
                        DataRow svnRow = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Statyczne.BranczeSVN, branczSvn);
                        if (svnRow.IsNull())
                        {
                            FormMain.Instance.ShowDxErrorDialog("Nie można odnalećś url dla brancza.");
                            return null ;
                        }
                        string svnUrl = svnRow["URL"].AsString().TrimEnd('/');
                        if (addUrl)
                            paramUrl = " /url:" + svnUrl;
                        if (urlAsPath)
                            path = svnUrl.AddDoubleQuotes();
                    }
                    param = "/command:" + command + (pathFile.IsNullOrEmpty() ? " /path:" + path : " /pathfile:" + pathFile.AddDoubleQuotes() + " /deletepathfile") + paramUrl + " /closeonend:0";
                    Process p = Process.Start(file, param);

                    if (param.XMatch("/command:\\s*commit"))
                    {
                        if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Tortoise.AutoAddLogAfterCommit))
                        {
                            TryAddLogAfterCommit(p, path);
                        }
                    }
                    return p;
                }
                return null;
            }
            public static Process RunTortoiseCmdForFile(string path, string cmd)
            {
                if (CanUseTortoiseProc())
                {
                    string file = GetTortoiseProcPath();

                    if ((!path.StartsWith("\"") || !path.EndsWith("\"")) && path != ".")
                        path = path.AddDoubleQuotes();

                    string param = "";

                    param = "/command:" + cmd + " /path:" + path + " /closeonend:0";
                    Process p = Process.Start(file, param);

                    return p;
                }
                return null;
            }
            public static Process ShowTortoiseLogForFile(string path)
            {
                return RunTortoiseCmdForFile(path, "log");
            }
            public static Process ShowTortoiseBlameForFile(string path)
            {
                return RunTortoiseCmdForFile(path, "blame");
            }

            public static void AddSvnToPath(Process p)
            {
                string path = GetTortoiseSvnPath();
                if (path.IsNull())
                {
                    p.Echo("Brak svn.exe. Ustaw opcje.");
                    FormMain.ShowWarningAlert("Brak svn.exe. Sprawdź opcje");
                }
                else
                {
                    try
                    {
                        p.Execute("set PATH=%PATH%;" + Path.GetDirectoryName(path));
                    }
                    catch { }
                }
            }
            public static string GetTortoiseSvnPath()
            {
                return OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseSvn);
            }
            public static string GetDefaultTortoiseSvnPath()
            {
                string str = "";
                try
                {
                    str = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\TortoiseSVN", "Directory", "").AsString();
                    if (str.IsNull() || !Directory.Exists(str))
                        str = "";
                    else
                    {
                        str = str.TrimEnd('\\') + "\\bin\\svn.exe";
                        if (!File.Exists(str))
                            str = "";
                    }
                }
                catch { str = ""; }
                return str;
            }
            public static string GetTortoiseProcPath()
            {
                return OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseProc);
            }
            public static string GetDefaultTortoiseProcPath()
            {
                string str = "";
                try
                {
                    str = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\TortoiseSVN", "ProcPath", "").AsString();
                    if (str.IsNull() || !File.Exists(str))
                        str = "";
                }
                catch { str = ""; }
                return str;
            }
            private static bool CanUseTortoiseProc()
            {
                string file = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseProc);
                bool res = false;
                try
                {
                    if (file.IsNotNullOrWhiteSpace())
                    {
                        res = File.Exists(file);
                    }
                }
                catch { }
                return res;
            }
            public static bool CanUseTortoiseSvn()
            {
                string file = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.Rozne.TortoiseSvn);
                bool res = false;
                try
                {
                    if (file.IsNotNullOrWhiteSpace())
                    {
                        res = File.Exists(file);
                    }
                }
                catch { }
                return res;
            }
            private static Process GetDirectoriesProcess = null;
            
            private static List<string> GetDirectoriesList = new List<string>();
            public static string[] GetDirectories(string path)
            {
                while (GetDirectoriesProcess != null)
                {
                    Application.DoEvents();
                    if (Program.IsExit)
                        return new string[0];
                }
                GetDirectoriesList.Clear();
                if (CanUseTortoiseSvn())
                {
                    GetDirectoriesProcess = CreateCMDProcess(GetDirectories_Data);
                    AddSvnToPath(GetDirectoriesProcess);
                    GetDirectoriesProcess.Execute("svn list " + path);
                    GetDirectoriesProcess.Echo("exit");
                    while (GetDirectoriesProcess != null)
                    {
                        Application.DoEvents();
                        if (Program.IsExit)
                            return new string[0];
                    }
                }
                return GetDirectoriesList.ToArray();
            }
            private static void GetDirectories_Data(object sender, DataReceivedEventArgs e)
            {
                if (e.Data.AsString().EndsWith("/"))
                    GetDirectoriesList.Add(e.Data.TrimEnd('/'));
                else if (e.Data.AsString() == "exit")
                {
                    try
                    {
                        GetDirectoriesProcess.KillProcessTree();
                        GetDirectoriesProcess.Dispose();
                    }
                    catch { }
                    GetDirectoriesProcess = null;
                }
            }
            public static string GetLogMessage()
            {
                string cr = "";
                string summary = "";

                string s = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Commit.PochodzenieMessage);
                bool isHist = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Commit.DodajHistorie);

                switch (s)
                {
                    case "SD": //SoftDev CR
                        string PochodzenieCra = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Commit.PochodzenieCra);
                        
                        if(PochodzenieCra == "A" || PochodzenieCra == "AW")
                            SoftDevTools.GetCRInfo(true, false, true, SoftDevTools.GetInfoFromSDForHistory);
                        else
                            SoftDevTools.GetCRInfo(false, isHist, true, SoftDevTools.GetInfoFromSDForHistory);
                        if (PochodzenieCra == "A")
                        {
                            cr = SoftDevTools.CR;
                            summary = SoftDevTools.Summary;
                        }
                        else
                        {
                            BuildHelper.GlobalTools.SoftDevTools.CRInfo info = BuildHelper.Work.Tools.Forms.WyborCRa.ShowCRDialog(PochodzenieCra == "AW");
                            if (info != null)
                            {
                                cr = info.Numer;
                                summary = info.Summary;
                            }
                            else
                            {
                                return null;
                            }
                        }
                        if (cr.IsNotNull())
                        {
                            string last = "";
                            if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Commit.UzyjOstatniegoMsgDlaCra))
                                last = GetLastLogMessageForCR(cr);
                            if (last.IsNotNull())
                                return last;
                            string msg = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Commit.CRPrefix);
                            msg += cr;
                            if (summary.IsNotNull() && OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Commit.DodajSummarry))
                                msg += Constants.NewLineLinux + summary;
                            return msg;
                        }
                        break;
                    case "N": //Brak Message
                        return "";
                    case "P": //Sam Prefix
                        return OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Commit.CRPrefix);
                }
                return "";
            }
            struct PochodzenieCRA
            {
                public const string OtwartyWSD = "OSD";
                public const string WybierzZSD = "WSD";
            }
            public static List<string> GetHistoryLogMessages()
            {
                List<string> messages = new List<string>();
                try
                {
                    RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\TortoiseSVN\\History");
                    if (reg != null)
                    {
                        string[] sub = reg.GetSubKeyNames();
                        if (sub != null)
                        {
                            foreach (string s in sub)
                            {
                                if (s.XMatch("commit"))
                                {
                                    RegistryKey k = reg.OpenSubKey(s);
                                    List<string> list = new List<string>(k.GetValueNames());
                                    list.SortAsStringWithNumberWords();
                                    foreach (string ss in list)
                                    {
                                        string val = k.GetValue(ss).AsString();
                                        messages.AddIfNotExist(val);
                                    }
                                }
                            }
                        }
                    }
                }
                catch { }
                return messages;
            }

            public static string GetLastLogMessageForCR(string CR)
            {
                string str = "";
                try
                {
                    RegistryKey reg = Registry.CurrentUser.OpenSubKey("Software\\TortoiseSVN\\History");
                    if (reg != null)
                    {
                        string[] sub = reg.GetSubKeyNames();
                        if (sub != null)
                        {
                            foreach (string s in sub)
                            {
                                if (s.XMatch("commit"))
                                {
                                    RegistryKey k = reg.OpenSubKey(s);
                                    List<string> list = new List<string>(k.GetValueNames());
                                    list.Sort();
                                    foreach (string ss in list)
                                    {
                                        string val = k.GetValue(ss).AsString();
                                        if (val.XMatch(CR))
                                            return val;
                                    }
                                }
                            }
                        }
                    }
                        
                }
                catch { }
                return str;
            }
        }

        #endregion
        #region DBTools
        public static class DBTools
        {
            #region Connection Strings
            static RegexOptions op = RegexOptions.IgnoreCase | RegexOptions.Singleline;
                    
            static string BHGroup = "# Build Helper Connections #(.*?)# End Of Build Helper Connections #";
            static string BHEnvGroup = "# Env [ENV] #(.*?)#";

            static string sidPart =
@"
[NAME] =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = [HOST])(PORT = [PORT]))
    )
    (CONNECT_DATA =
      (SID = [SID])
    )
  )
";
            static string servicePart =
@"
[NAME] =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = [HOST])(PORT = [PORT]))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = [SERVICE])
    )
  )
";

            #endregion
            public static string GetCorrectEnvName(string env)
            {
                env = env.XReplace("[^\\w]+", "_");
                return env;
            }
            private static string AddTnsNames(string bhg, string env, string host, string port, string service, string sid)
            {
                env = GetCorrectEnvName(env);
                
                bhg = bhg.XReplace(BHEnvGroup.Replace("[ENV]", env.XEscape())+"\\s*", "", op).Trim();
                
                string part = "# Env " + env + " #";
                if (sid.IsNotNull())
                {
                    part += sidPart;
                    part = part.Replace("[SID]", sid);
                }
                else
                {
                    part += servicePart;
                    part = part.Replace("[SERVICE]", service);
                }
                part = part.Replace("[HOST]", host);
                part = part.Replace("[PORT]", port);
                part = part.Replace("[NAME]", env);
                part += "#";
                bhg = part + Constants.NewLineLinux + bhg;
                bhg = bhg.Trim();

                return bhg;
            }

            public static bool AddTnsNames(string env, string host, string port, string service, string sid)
            {
                bool result = false;
                try
                {
                    string tnsnames = Environment.GetEnvironmentVariable("ORACLE_HOME") + @"\network\admin\tnsnames.ora";
                    if (File.Exists(tnsnames))
                    {
                        string content = tnsnames.ReadFile();
                        if (!content.XMatch(BHGroup, op))
                            content += Constants.NewLineLinux + BHGroup.Replace("(.*?)", Constants.NewLineLinux) + Constants.NewLineLinux;
                        
                        string bhg = content.GetFirstMatch(BHGroup, 1, op);
                        bhg = AddTnsNames(bhg, env, host, port, service, sid);
                        content = content.XReplace(BHGroup, BHGroup.Replace("(.*?)", Constants.NewLineLinux + bhg + Constants.NewLineLinux), op);
                        content = content.Trim();
                        content.WriteToFile(tnsnames, writeLine: false);
                        result = true;
                    }
                    else
                    {
                        ("Plik " + tnsnames + " nie istnieje.").LogError();
                        FormMain.ShowErrorAlert("Plik tnsnames.ora nie istnieje.\nSprawdz zmienną ORACLE_HOME.");
                    }
                }
                catch (Exception ex)
                {
                    ex.Log();
                    FormMain.ShowErrorAlert("Wystąpił problem podczas dodawania wpisów do tnsnames.ora. Sprawdź logi.");
                }
                return result;
            }
            
            public static bool AddTns(DataRow r)
            {
                string host = r["STP_BD_HOST"].AsString().Trim();
                string sid = r["STP_BD_SID"].AsString().Trim();
                string service = r["STP_BD_SERVICE"].AsString().Trim();
                string port = r["STP_BD_PORT"].AsString().Trim();
                string env = r["STP_BD_NAZWA"].AsString().Trim();

                return AddTnsNames(env, host, port, service, sid);
            }

            public static bool AddTns(DataTable dt)
            {
                DataRow[] rows = dt.Select();
                bool result = false;
                try
                {
                    if (rows.Length > 0)
                    {
                        string tnsnames = Environment.GetEnvironmentVariable("ORACLE_HOME") + @"\network\admin\tnsnames.ora";
                        if (File.Exists(tnsnames))
                        {
                            string content = tnsnames.ReadFile();
                            if (!content.XMatch(BHGroup, op))
                                content += Constants.NewLineLinux + BHGroup.Replace("(.*?)", Constants.NewLineLinux) + Constants.NewLineLinux;

                            string bhg = content.GetFirstMatch(BHGroup, 1, op);

                            foreach (DataRow r in rows)
                            {
                                string host = r["STP_BD_HOST"].AsString().Trim();
                                string sid = r["STP_BD_SID"].AsString().Trim();
                                string service = r["STP_BD_SERVICE"].AsString().Trim();
                                string port = r["STP_BD_PORT"].AsString().Trim();
                                string env = r["STP_BD_NAZWA"].AsString().Trim();

                                bhg = AddTnsNames(bhg, env, host, port, service, sid);
                            }
                            content = content.XReplace(BHGroup, BHGroup.Replace("(.*?)", Constants.NewLineLinux + bhg + Constants.NewLineLinux), op);
                            content.WriteToFile(tnsnames, writeLine:false);
                            result = true;
                        }
                        else
                        {
                            ("Plik " + tnsnames + " nie istnieje.").LogError();
                            FormMain.ShowErrorAlert("Plik tnsnames.ora nie istnieje.\nSprawdz zmienną ORACLE_HOME.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    ex.Log();
                    FormMain.ShowErrorAlert("Wystąpił problem podczas dodawania wpisów do tnsnames.ora. Sprawdź logi.");
                }
                return result;
            }
            
            public static string GetPlSqlDeveloperPath()
            {
                string str = "";
                try
                {
                    string pf = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles).AsString().TrimEnd('\\');
                    string[] dirs = Directory.GetDirectories(pf, "PLSQL Developer*");
                    if (dirs != null)
                    {
                        string file;
                        foreach (string d in dirs)
                        {
                            file = d.TrimEnd('\\') + "\\plsqldev.exe";
                            if (File.Exists(file))
                            {
                                str = file;
                                break;
                            }
                        }
                    }
                }
                catch { str = ""; }
                return str;
            }

            public static bool CanUsePlSqlDeveloper()
            {
                string file = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.Definicje_Group.BazyDanych.PlSqlDeveloper);
                bool res = false;
                try
                {
                    if (file.IsNotNullOrWhiteSpace())
                    {
                        res = File.Exists(file);
                    }
                }
                catch { }
                return res;
            }

            public static string GetSqlToolsPath()
            {
                string str = "";
                try
                {
                    string pf = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles).AsString().TrimEnd('\\');
                    string[] dirs = Directory.GetDirectories(pf, "SqlTools*");
                    if (dirs != null)
                    {
                        string file;
                        foreach (string d in dirs)
                        {
                            file = d.TrimEnd('\\') + "\\sqltools.exe";
                            if (File.Exists(file))
                            {
                                str = file;
                                break;
                            }
                        }
                    }
                }
                catch { str = ""; }
                return str;
            }

            public static bool CanUseSqlTools()
            {
                string file = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.Definicje_Group.BazyDanych.SqlTools);
                bool res = false;
                try
                {
                    if (file.IsNotNullOrWhiteSpace())
                    {
                        res = File.Exists(file);
                    }
                }
                catch { }
                return res;
            }
        }

        #endregion
        #region ProcessTools
        public static class ProcessTools
        {
            public static void SetEnvVariable(Process process, string variable, string value)
            {
                if (value.IsNull())
                {
                    process.StartInfo.EnvironmentVariables.Remove(variable);
                    value = "".AddDoubleQuotes();
                }
                else
                    process.StartInfo.EnvironmentVariables[variable] = value;

                if (process.StartInfo.FileName == "cmd.exe")
                    process.Execute("set " + variable + "=" + value);
            }
            public static void SetEnvVariable(Process process, Dictionary<string, string> vars)
            {
                if (vars != null)
                {
                    foreach (KeyValuePair<string, string> kvp in vars)
                        SetEnvVariable(process, kvp.Key, kvp.Value);
                }
            }
            public static void SetEnvVariable(Process process, string brancz)
            {
                SetEnvVariable(process, Setup.Brancze.BranczeTools.GetZmienneBrancza(brancz));
            }

            public static List<Process> GetProcessByFile(string path)
            {
                List<Process> list = new List<Process>();
                Process[] proc = Process.GetProcesses();
                foreach (Process p in proc)
                {
                    try
                    {
                        if (p.MainModule != null && p.MainModule.FileName.ToUpper() == path.ToUpper())
                        {
                            list.Add(p);
                        }
                    }
                    catch { }
                }
                return list;
            }

            public static Process GetRunningProcessByCommandLine(string processName, string commandLine)
            {
                Process[] pr = Process.GetProcessesByName(processName);
                return GetRunningProcessByCommandLine(pr, commandLine);
            }
            public static Process GetRunningProcessByWindowText(string processName, string windowText)
            {
                Process[] pr = Process.GetProcessesByName(processName);
                return GetRunningProcessByWindowText(pr, windowText);
            }
            public static Process GetRunningProcessByWindowText(Process[] processes, string windowText)
            {
                if (processes != null)
                {
                    string text;
                    foreach (Process p in processes)
                    {
                        text = Win32.GetWindowText(p.MainWindowHandle);
                        if (windowText.IsNull() || text.XMatch(windowText))
                            return p;
                    }
                }
                return null;
            }
            public static Process GetRunningProcessByCommandLine(Process[] processes, string commandLine)
            {
                if (processes != null)
                {
                    foreach (Process p in processes)
                    {
                        if (commandLine.IsNull() || p.GetProcessInfo(ProcessInfo.CommandLine).AsString().XMatch(commandLine))
                            return p;
                    }
                }
                return null;
            }

            public static bool IsProcessReadyForEvents(Process p)
            {
                bool res = false;
                try
                {
                    if (p != null && !p.HasExited)
                    {
                        res = true;
                    }
                }
                catch { }
                return res;
            }
        }

        public static Process CreateCMDProcess(DataReceivedEventHandler process_ErrorDataReceived)
        {
            Process process = new Process();
            ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
            psi.CreateNoWindow = true;
            psi.UseShellExecute = false;
            psi.RedirectStandardError = true;
            psi.RedirectStandardInput = true;
            psi.RedirectStandardOutput = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo = psi;
            if (process_ErrorDataReceived != null)
            {
                process.ErrorDataReceived += process_ErrorDataReceived;
                process.OutputDataReceived += process_ErrorDataReceived;
            }
            process.StartInfo = psi;
            process.Start();
            process.BeginErrorReadLine();
            process.BeginOutputReadLine();
            process.EchoOff();
            return process;
        }
        #endregion
        #region ServerTools
        public static class ServerTools
        {
            public static void SearchDB()
            {
                SqlCeDataManager m = CreateManager();
                Setup.Serwery.SeweryDataSet.STP_SERWERYDataTable dt = new Setup.Serwery.SeweryDataSet.STP_SERWERYDataTable();
                m.AddTableDef(dt, "SELECT * FROM STP_SERWERY");
                m.FillTable(dt);
                foreach (DataRow srvRow in dt.Rows)
                {
                    string db = "";
                    string typ = srvRow["STP_SRW_TYP"].AsString();
                    string katalogSerwera = srvRow["STP_SRW_DIR"].AsString().TrimEnd('\\');
                    switch (typ)
                    {
                        case ServerType.JBoss4:
                        case ServerType.JBoss5:
                            string instancja = srvRow["STP_SRW_INSTANCJA"].AsString();
                            if (instancja.IsNull())
                                instancja = "default";
                            string file = katalogSerwera + @"\server\" + instancja + @"\deploy\gcm-ds.xml";
                            string tmp = file.ReadFile();
                            string dbuser = tmp.GetFirstMatch("<user-name>(.*?)</user-name>");
                            string host = tmp.GetFirstMatch("<connection-url>jdbc:oracle:thin:@(.*?):\\d*[/:](.*?)</connection-url>");
                            string serviceSid = tmp.GetFirstMatch("<connection-url>jdbc:oracle:thin:@(.*?):\\d*[/:](.*?)</connection-url>", 2);

                            DataTable dtDB = BrowserCache.GetBrowserData(Init.InitFormBrowserNames.Setup.BazyDanych);
                            DataRow dbRow = dtDB.SelectFirstRow("STP_BD_HOST = " + host.EscapeSql() + " AND STP_BD_USER = " + dbuser.EscapeSql() + " AND ("
                                + " STP_BD_SID = " + serviceSid.EscapeSql() + " OR  STP_BD_SERVICE = " + serviceSid.EscapeSql() + ")");
                            if (dbRow != null)
                            {
                                db = dbRow["STP_BD_NAZWA"].AsString();
                                srvRow["STP_SRW_LAST_DB"] = db;
                                m.UpdateTable(dt);
                            }
                            break;
                        default:
                            //FormMain.Instance.ShowDxInfoDialog("Serwer " + typ + " nie jest wspierany.");
                            return;
                    }
                }
                BrowserCache.RefreshCacheForTable("STP_SERWERY");
            }

            public const string MSG_DATA_SOURCE_ZMIENIONY = "Data Source Zmieniony";
            public static class ServerType
            {
                public const string JBoss4 = "jboss4";
                public const string JBoss5 = "jboss5";
                public const string OAS = "oas";
                public const string WebLogic = "weblogic";
            }
            public enum ServerRestartType
            {
                Restart,
                DoNotRestart,
                Ask
            }

            private static Dictionary<int, Process> _Serwers = new Dictionary<int, Process>();
            public static Dictionary<int, Process> Serwers
            {
                get { return _Serwers; }
            }

            public static Process GetSerwerProcess(int serwer)
            {
                Process[] proc = Process.GetProcessesByName("cmd");
                SqlCeDataManager m = CreateManager();
                string bat = m.ExecuteScalar("SELECT STP_SRW_START_BAT FROM STP_SERWERY WHERE STP_SRW_ID = " + serwer).AsString().Trim();
                m.Dispose();

                if (bat.IsNotNull())
                {
                    foreach (Process p in proc)
                    {
                        if (p.GetProcessInfo(ProcessInfo.CommandLine).AsString().XMatch(bat.XEscape(), System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                        {
                            return p;
                        }
                    }
                }
               
                return null;
            }
            public static void SearchForSerwers()
            {
                DataTable dt = BrowserCache.GetBrowserData(Init.InitFormBrowserNames.Setup.Serwery, true);
                if (dt != null)
                {
                    DataTable dt2 = dt.Copy();
                    int serwer;
                    foreach (DataRow r in dt2.Rows)
                    {
                        serwer = r["STP_SRW_ID"].AsInt();
                        SearchForSerwers(serwer);
                    }
                }
            }
            public static Process SearchForSerwers(int serwer)
            {
                Process p = GetSerwerProcess(serwer);
                if (p != null)
                    Serwers[serwer] = p;
                else if (Serwers.ContainsKey(serwer))
                    Serwers.Remove(serwer);
                return p;
            }
            public static void RunServer(int serwer, string brancz, bool bringToFront = false, ServerRestartType restartType = ServerRestartType.DoNotRestart)
            {
                SqlCeDataManager m = CreateManager();
                Setup.Serwery.SeweryDataSet.STP_SERWERYDataTable dt = new Setup.Serwery.SeweryDataSet.STP_SERWERYDataTable();
                m.AddTableDef(dt, "SELECT * FROM STP_SERWERY WHERE STP_SRW_ID = " + serwer);
                m.FillTable(dt);

                DataRow srvRow = dt.SelectFirstRow();
                if (srvRow != null)
                {
                    try
                    {
                        Process p = SearchForSerwers(serwer);
                        if (p != null)
                        {
                            if (restartType == ServerRestartType.Ask)
                            {
                                if (FormMain.Instance.ShowDxYNQuestionDialog("Serwer jest już uruchomiony. Chcesz go zrestartować?") == System.Windows.Forms.DialogResult.No)
                                {
                                    if (bringToFront && p.MainWindowHandle != IntPtr.Zero)
                                    {
                                        p.BringWindowToFront();
                                    }
                                    return;
                                }
                            }
                            else if (restartType == ServerRestartType.DoNotRestart)
                            {
                                FormMain.ShowWarningAlert("Server jest już uruchomiony");
                                return;
                            }
                            else
                            {
                                FormMain.ShowWarningAlert("Server jest już uruchomiony i zostanie zrestartowany.");
                            }
                        }
                        else
                        {
                            bringToFront = true;
                        }

                        if (p != null)
                        {
                            try
                            {
                                p.KillProcessTree();
                                p.Dispose();
                            }
                            catch { }
                            p = null;
                        }

                        string bat = srvRow["STP_SRW_START_BAT"].AsString();
                        string nazwa = srvRow["STP_SRW_NAZWA"].AsString();

                        string lastBr = srvRow["STP_SRW_LAST_BR"].AsString();
                        if (lastBr.IsNotNull())
                            nazwa += " ( " + lastBr + " )";
                        else if (brancz.IsNotNull())
                            nazwa += " ( " + brancz + " )";
                        

                        string db = srvRow["STP_SRW_LAST_DB"].AsString();
                       
                        string typ = srvRow["STP_SRW_TYP"].AsString();
                        string katalogSerwera = srvRow["STP_SRW_DIR"].AsString().TrimEnd('\\');
                        if (db.IsNull() )
                        {
                            switch (typ)
                            {
                                case ServerType.JBoss4:
                                case ServerType.JBoss5:
                                    {
                                        string instancja = srvRow["STP_SRW_INSTANCJA"].AsString();
                                        if (instancja.IsNull())
                                            instancja = "default";
                                        string file = katalogSerwera + @"\server\" + instancja + @"\deploy\gcm-ds.xml";
                                        string tmp = file.ReadFile();
                                        string dbuser = tmp.GetFirstMatch("<user-name>(.*?)</user-name>");
                                        string host = tmp.GetFirstMatch("<connection-url>jdbc:oracle:thin:@(.*?):\\d*[/:](.*?)</connection-url>");
                                        string serviceSid = tmp.GetFirstMatch("<connection-url>jdbc:oracle:thin:@(.*?):\\d*[/:](.*?)</connection-url>", 2);

                                        DataTable dtDB = BrowserCache.GetBrowserData(Init.InitFormBrowserNames.Setup.BazyDanych);
                                        DataRow dbRow = dtDB.SelectFirstRow("STP_BD_HOST = " + host.EscapeSql() + " AND STP_BD_USER = " + dbuser.EscapeSql() + " AND ("
                                            + " STP_BD_SID = " + serviceSid.EscapeSql() + " OR  STP_BD_SERVICE = " + serviceSid.EscapeSql() + ")");
                                        if (dbRow != null)
                                        {
                                            db = dbRow["STP_BD_NAZWA"].AsString();
                                            srvRow["STP_SRW_LAST_DB"] = db;
                                            m.UpdateTable(dt);
                                            BrowserCache.RefreshCacheForTable("STP_SERWERY");
                                        }
                                    }
                                    break;
                                default:
                                    //FormMain.Instance.ShowDxInfoDialog("Serwer " + typ + " nie jest wspierany.");
                                    break;
                            }
                        }
                        if (db.IsNotNull())
                        {
                            nazwa += " [ DB: " + db + " ]";
                        }
                        ProcessStartInfo s = new ProcessStartInfo("cmd.exe", "/c title=" + nazwa.AddDoubleQuotes()+" & " + bat.AddDoubleQuotes());
                        s.WorkingDirectory = Path.GetDirectoryName(bat);
                        if (!bringToFront)
                            s.WindowStyle = ProcessWindowStyle.Minimized;

                        Process proc = new Process();
                        proc.StartInfo = s;
                        proc.Start();
                        SearchForSerwers(serwer);
                    }
                    catch (Exception ex)
                    {
                        ex.Log();
                    }
                }
                m.Dispose();

            }
            
            public static bool IsServerRunning(int server)
            {
                return SearchForSerwers(server) != null;
            }

            public static void ChangeDataSource(Process process, int server, int db)
            {
                SqlCeDataManager m = CreateManager();
                
                Setup.Serwery.SeweryDataSet ds = new Setup.Serwery.SeweryDataSet();
                m.AddTableDef(ds.STP_SERWERY, "SELECT * FROM STP_SERWERY WHERE STP_SRW_ID = " + server);
                m.FillTable(ds.STP_SERWERY);
                Setup.BazyDanych.BazyDanychDataSet dsDb = new Setup.BazyDanych.BazyDanychDataSet();
                m.AddTableDef(dsDb.STP_BAZY_DANYCH, "SELECT * FROM STP_BAZY_DANYCH WHERE STP_BD_ID = " + db);
                m.FillTable(dsDb.STP_BAZY_DANYCH);

                if (ds.STP_SERWERY.Rows.Count == 1 && dsDb.STP_BAZY_DANYCH.Rows.Count == 1)
                {
                    DataRow srvRow = ds.STP_SERWERY[0];
                    DataRow dbRow = dsDb.STP_BAZY_DANYCH[0];
                    string typ = srvRow["STP_SRW_TYP"].AsString();
                    string katalogSerwera = srvRow["STP_SRW_DIR"].AsString().TrimEnd('\\');
                    string jndi = srvRow["STP_SRW_DS_JNDI"].AsString();

                    string dbUser = dbRow["STP_BD_USER"].AsString();
                    string dbPass = dbRow["STP_BD_PASS"].AsString();
                    string dbHost = dbRow["STP_BD_HOST"].AsString();
                    string dbPort = dbRow["STP_BD_PORT"].AsString();
                    string dbSid = dbRow["STP_BD_SID"].AsString();
                    string dbService = dbRow["STP_BD_SERVICE"].AsString();
                    string hostPortSid = dbHost + ":" + dbPort + (dbSid.IsNotNull() ? (":" + dbSid) : ("/" + dbService));
                    string url = hostPortSid;
                    srvRow["STP_SRW_LAST_DB"] = dbRow["STP_BD_NAZWA"];
                    m.UpdateTable(ds.STP_SERWERY);
                    BrowserCache.RefreshCacheForTable("STP_SERWERY");
                    switch (typ)
                    {
                        case ServerType.OAS:
                            {
                                string userName = srvRow["STP_SRW_LOGIN"].AsString();
                                string pass = srvRow["STP_SRW_HASLO"].AsString();
                                string dsNazwa = srvRow["STP_SRW_DS_NAZWA"].AsString();

                                katalogSerwera += @"\j2ee\home";
                                process.CdDir(katalogSerwera);
                                string cmdAdd = " -addNativeDataSource -name " + dsNazwa +
                                    " -dbUser " + dbUser +
                                    " -dbPassword " + dbPass +
                                    " -jndiLocation " + jndi +
                                    " -url " + url;
                                string cmdRemove = "-removeNativeDataSource -name " + dsNazwa;
                                process.Execute("java -jar admin_client.jar " + cmdRemove);
                                process.Execute("java -jar admin_client.jar " + cmdAdd);
                                process.Echo(MSG_DATA_SOURCE_ZMIENIONY + " user:" + dbUser + "; pass:" + dbPass + "; url:" + hostPortSid);
                            }
                            break;
                        case ServerType.JBoss4:
                        case ServerType.JBoss5:
                            {
                                string template = srvRow["STP_SRW_DS_TEMPLATE"].AsString();
                                template = template.Replace("[JNDI_NAME]", jndi);
                                template = template.Replace("[URL]", url);
                                template = template.Replace("[USER]", dbUser);
                                template = template.Replace("[PASS]", dbPass);
                                string instancja = srvRow["STP_SRW_INSTANCJA"].AsString();
                                if (instancja.IsNull())
                                    instancja = "default";
                                string file = katalogSerwera + @"\server\" + instancja + @"\deploy\gcm-ds.xml";
                                template.WriteToFile(file, Encoding.Default, writeLine:false);
                                process.Echo(MSG_DATA_SOURCE_ZMIENIONY + " user:" + dbUser + "; pass:" + dbPass + "; url:" + hostPortSid);
                            }
                            break;
                        default:
                            process.Echo(GlobalTools.Messages.MSG_ERROR + " Server " + typ + " nie jest wspierany.");
                            break;
                    }
                }
                else
                {
                    process.Echo(GlobalTools.Messages.MSG_ERROR + " Nie mozna znaleźć serwera lub bazy danych.");
                }
                m.Dispose();
            }
        }
        #endregion

        #region FilesTools
        public static class FilesTools
        {
            public class DevEnvInfo
            {
                public Process DevEnv { get; private set; }
                public string CommandLine { get; private set; }
                public DevEnvInfo(Process devenv)
                {
                    DevEnv = devenv;
                    CommandLine = devenv.GetProcessInfo(ProcessInfo.CommandLine).AsString();
                }
            }

            public static List<DevEnvInfo> GetDevEnvs()
            {
                List<DevEnvInfo> list = new List<DevEnvInfo>();
                Process[] devenvs = Process.GetProcessesByName("devenv");
                foreach (Process p in devenvs)
                {
                    list.Add(new DevEnvInfo(p));
                }
                return list;
            }
            public static bool IsDevEnvOpened(string file)
            {
                return GetDevEnv(file) != null;
            }
            public static Process GetDevEnv(string file)
            {
                return GetDevEnv(file, GetDevEnvs());
            }
            public static Process GetDevEnv(string file, List<DevEnvInfo> devenvs)
            {
                if (devenvs.Count > 0)
                {
                    foreach (var p in devenvs)
                    {
                        if (p.CommandLine.XMatch(file.XEscape()))
                        {
                            return p.DevEnv;
                        }
                    }
                }
                return null;
            }

            public static string GetTemplLogFile(string prefix, string ext = "log")
            {
                string fName = "";
                if (prefix.IsNotNull())
                    fName = prefix + "_";
                fName += Path.GetRandomFileName() + "." + ext;
                return TmpLogsDir + "\\" + fName;
            }
            public static string TmpLogsDir
            {
                get;
                set;
            }
            public static void InitLogsDir()
            {
                TmpLogsDir = Application.StartupPath + "\\TmpLogs";
                ClearTmpLogsDir();
                if (!Directory.Exists(TmpLogsDir))
                    Directory.CreateDirectory(TmpLogsDir);
            }
            public static void ClearTmpLogsDir()
            {
                if (Directory.Exists(TmpLogsDir))
                {
                    try
                    {
                        Directory.Delete(TmpLogsDir, true);
                    }
                    catch { }
                }
            }
            public enum FileOptions
            {
                None,
                Extract,
                Select
            }
            public static bool OpenFileInDevEnv(string file, int goToLine = -1, int goToCol = -1)
            {
                string root = file.GetFirstMatch("(.*\\\\apps\\\\[\\w]*\\\\src\\\\gui\\\\[\\w]*\\\\)").XEscape();
                string root2 = file.GetFirstMatch("(.*\\\\apps\\\\[\\w]*\\\\src\\\\gui\\\\)").XEscape();
                
                Process devenv = null;
                Process[] pr = Process.GetProcessesByName("devenv");
                if (pr.Length > 0)
                {
                    devenv = ProcessTools.GetRunningProcessByCommandLine(pr, root);
                    bool run = false;
                    if (devenv != null)
                        run = OpenFileInDevEnv(devenv, file, goToLine, goToCol);
                    
                    if (!run)
                    {
                        devenv = ProcessTools.GetRunningProcessByCommandLine(pr, root2);
                        if (devenv != null)
                            run = OpenFileInDevEnv(devenv, file, goToLine, goToCol);
                    }
                    if (!run)
                    {
                            devenv = ProcessTools.GetRunningProcessByCommandLine(pr, "Soft[\\w]*\\\\");
                            if (devenv != null)
                                run = OpenFileInDevEnv(devenv, file, goToLine, goToCol);
                    }
                    if (!run)
                    {
                        devenv = pr[0];
                        run = OpenFileInDevEnv(devenv, file, goToLine, goToCol);
                    }
                    return run;
                }
                return false;
            }
            private static bool OpenFileInDevEnv(Process devenv, string file, int goToLine = -1, int goToCol = -1)
            {
                bool result = true;
                if (devenv != null)
                {
                    EnvDTE.DTE obj = ProgNetComponents.Tools.Coding.GetOpenedDevenv(devenv);
                    int idx = 0;
                    while (idx < 3)
                    {
                        try
                        {
                            obj.ExecuteCommand("Edit.OpenFile", file);
                            idx = 3;
                        }
                        catch
                        {
                            idx++;
                            if (idx == 3)
                                result = false;
                            System.Threading.Thread.Sleep(10);
                        }
                    } 
                    if (!result)
                        return false;
                    if (goToLine > -1)
                    {
                        idx = 0;
                        while (idx < 3)
                        {
                            try
                            {
                                obj.ExecuteCommand("Edit.GoTo", goToLine.ToString());
                                idx = 3;
                            }
                            catch
                            {
                                idx++;
                                if (idx == 3)
                                    result = false;
                                System.Threading.Thread.Sleep(10);
                            }
                        }
                        if (!result)
                            return false;
                        try
                        {
                            if (goToCol > -1)
                            {
                                if (obj.ActiveDocument != null && obj.ActiveDocument.Selection != null)
                                {
                                    EnvDTE.TextSelection sel = obj.ActiveDocument.Selection as EnvDTE.TextSelection;
                                    if (sel != null)
                                        sel.MoveToDisplayColumn(goToLine, goToCol);
                                }
                            }
                        }
                        catch
                        {
                            result = false;
                        }
                    }
                    devenv.BringWindowToFront();
                    return true;
                }
                return false;
            }
            
            public static void AttachDebugger(Process p, Process devenv)
            {
                try
                {
                    if (devenv != null)
                    {
                        EnvDTE.DTE obj = ProgNetComponents.Tools.Coding.GetOpenedDevenv(devenv);
                        if (obj != null)
                        {
                            foreach (EnvDTE.Process proc in obj.Debugger.LocalProcesses)
                            {
                                if (proc.ProcessID == p.Id)
                                {
                                    proc.Attach();
                                    return;
                                }
                            }
                        }
                    }
                }
                catch { }
            }
            
            public static Process RunFile(string file, string type = "")
            {
                Process p = null;
                if (file.IsNotNull())
                {
                    try
                    {
                        FileInfo f = new FileInfo(file);
                        if (f.Exists)
                        {
                            p = Process.Start(f.FullName);
                        }
                        else
                        {
                            FormMain.Instance.ShowDxInfoDialog("Plik " + (type.IsNotNull() ? (type + " ") : "") + "nie istnieje.");
                        }
                    }
                    catch (Exception ex)
                    {
                        ex.Log();
                        FormMain.Instance.ShowDxErrorDialog("Błąd uruchamiania.");
                    }
                }
                else
                {
                    FormMain.Instance.ShowDxInfoDialog("Brak pliku" + (type.IsNotNull() ? (" " + type) : "") + ".");
                }
                return p;
            }
            public static bool RunFileUsingCmd(string file, string brancz = "", string type = "")
            {
                bool result = false;
                if (file.IsNotNull())
                {
                    try
                    {
                        FileInfo f = new FileInfo(file);
                        if (f.Exists)
                        {
                            using (Process p = CreateCMDProcess(null))
                            {
                                if (brancz.IsNotNull())
                                    ProcessTools.SetEnvVariable(p, brancz);
                                p.Execute("start " + type.AddDoubleQuotes() + " " + file.AddDoubleQuotes());
                                result = true;
                            }
                        }
                        else
                        {
                            FormMain.Instance.ShowDxInfoDialog("Plik " + (type.IsNotNull() ? (type + " ") : "") + "nie istnieje.");
                        }
                    }
                    catch (Exception ex)
                    {
                        ex.Log();
                        FormMain.Instance.ShowDxErrorDialog("Błąd uruchamiania.");
                    }
                }
                else
                {
                    FormMain.Instance.ShowDxInfoDialog("Brak pliku" + (type.IsNotNull() ? (" " + type) : "") + ".");
                }
                return result;
            }
            
            public const string MSG_KONIEC_POBIERANIA = "Koniec pobierania.";

            static int internalSdkId = 0;
            private class InternalSdkInfo
            {
                public InternalSdkInfo(int id, DataRow row)
                {
                    Id = id;
                    Row = row;
                }
                public int Id
                {
                    get;
                    set;
                }
                public DataRow Row
                {
                    get;
                    set;
                }
            }

            static Dictionary<Process, InternalSdkInfo> InternalSdkProc = new Dictionary<Process, InternalSdkInfo>();
            public static void GetBestInternalSdk(string brancz, bool showInfo, DataRow row)
            {
                DataRow r = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Brancze, brancz);
                string svnBrancz = brancz;
                if (r != null)
                {
                    svnBrancz = r["STP_BR_SVN"].AsString();
                }
                GetBestInternalSdk(svnBrancz, brancz, showInfo, row);
            }
            public static void GetBestInternalSdk(string branczForInternalSdk, string branczToExtract, bool showInfo, DataRow row)
            {
                Process p = CreateCMDProcess(GetBestInternalSdk_Data);
                InternalSdkProc.Add(p,  new InternalSdkInfo( internalSdkId, row));
                if (showInfo)
                    FormMain.ShowAlert("Pobieranie Internal Sdk\nBrancz:" + branczToExtract, null, new FormMain.AlertInfo(true, "INTERNAL_SDK_" + internalSdkId));
                internalSdkId++;
                p.EchoOff();
                GetBestInternalSdk(p, branczForInternalSdk, branczToExtract);
            }

            static void GetBestInternalSdk_Data(object sender, DataReceivedEventArgs e)
            {
                string str = e.Data.AsString();
                if (str.XMatch("^" + Messages.MSG_WARNING))
                    FormMain.ShowWarningAlert(str.GetFirstMatch("^" + Messages.MSG_WARNING + "(.*)"));
                if (str.XMatch("^" + Messages.MSG_INFO))
                    FormMain.ShowInfoAlert(str.GetFirstMatch("^" + Messages.MSG_INFO + "(.*)"));
                if (str.XMatch("^" + Messages.MSG_ERROR))
                {
                    FormMain.ShowErrorAlert(str.GetFirstMatch("^" + Messages.MSG_ERROR + "(.*)"));
                    SetStatus(InternalSdkProc[((Process)sender)].Row, BuildHelper.Scheduler.Zadanie.Statusy.Blad);
                }
                if (str.XMatch("The process cannot access the file because it is being used by another process"))
                {
                    FormMain.ShowErrorAlert(str);
                    SetStatus(InternalSdkProc[((Process)sender)].Row, BuildHelper.Scheduler.Zadanie.Statusy.Blad);
                }
                if (str.XMatch("^" + MSG_KONIEC_POBIERANIA) )
                {
                    if (sender is Process)
                    {
                        try
                        {
                            if (InternalSdkProc.ContainsKey((Process)sender))
                            {
                                if (InternalSdkProc[((Process)sender)].Row != null)
                                {
                                    try
                                    {
                                       SetStatus(InternalSdkProc[((Process)sender)].Row, BuildHelper.Scheduler.Zadanie.Statusy.Zakonczone);
                                    }
                                    catch (Exception ex) { ex.Log(); }
                                }
                                FormMain.CloseAlertById("INTERNAL_SDK_"+InternalSdkProc[((Process)sender)].Id);
                            }
                            ((Process)sender).KillProcessTree();
                            ((Process)sender).Dispose();
                        }
                        catch { }
                    }
                }
            }
            private static void SetStatus(DataRow row, string status)
            {
                if (FormMain.Instance.InvokeRequired)
                {
                    try
                    {
                        FormMain.Instance.Invoke(new Action<DataRow, string>(SetStatus), row, status);
                    }
                    catch { }
                    return;
                }
                try
                {
                    if (row["STATUS"].IsNull())
                        row["STATUS"] = status;
                }
                catch { }
            }
            
            public static void GetBestInternalSdk(Process process, string svnBrancz, string branczToExtract)
            {
                DataRow rExtract = BrowserCache.GetRowForValue(Init.InitFormBrowserNames.Setup.Brancze, branczToExtract);
                if (rExtract!=null)
                {
                    string svn = svnBrancz;
                    string katalog = rExtract["STP_BR_KATALOG"].AsString();
                    FileOptions options = FileOptions.None;
                    string op = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Narzedzia.InternalSdkGetType);
                    bool delete = false;

                    if (op == "E")
                    {
                        options = FileOptions.Extract;
                        delete = OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Narzedzia.DelInternalSdk);
                    }
                    else if (op == "O")
                        options = FileOptions.Select;

                    string katInternalSdk = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Setup_Group.URL.InternalSdk);
                    if (!string.IsNullOrEmpty(katInternalSdk))
                    {
                        katInternalSdk = katInternalSdk.TrimEnd('\\') + "\\" + svn;
                        DirectoryInfo dir = null;
                        try
                        {
                            dir = new DirectoryInfo(katInternalSdk);
                            if (dir.Exists)
                            {
                                FileInfo[] files = dir.GetFiles("*.exe");
                                FileInfo file = null;
                                if (files.Length == 0)
                                {
                                    process.Echo(Messages.MSG_ERROR + "Brak pliku z internal sdk.");
                                }
                                else if (files.Length == 1)
                                {
                                    file = files[0];
                                }
                                else
                                {
                                    process.Echo(Messages.MSG_WARNING + "Znaleziono wiele plików. Pobieranie najnowszego.");
                                    file = files[0];
                                    for (int i = 1; i < files.Length; i++)
                                    {
                                        if (file.CreationTime < files[i].CreationTime)
                                            file = files[i];
                                    }
                                }
                                if (file != null)
                                {
                                    process.Echo(Messages.MSG_INFO + "Data Pliku: " + file.CreationTime.ToString("g"));
                                    GetFile(process, file.FullName, katalog, options, delete);
                                }
                            }
                            else
                            {
                                process.Echo(Messages.MSG_ERROR + "Brak katalogu " + katInternalSdk);
                            }
                        }
                        catch (Exception ex)
                        {
                            ex.Log();
                            process.Echo(Messages.MSG_ERROR + ex.Message);
                        }
                    }
                    else
                    {
                        process.Echo(Messages.MSG_ERROR + "Brak katalogu Internal SDK. Sprawdź opcje.");
                    }
                }
            }

            public static void GetFile(Process process, string file, string distDir, FileOptions options, bool delete)
            {
                string fullName = distDir + "\\" + Path.GetFileName(file);
                try
                {
                    process.Execute("copy \"" + file + "\" \"" + fullName + "\" /Y");
                    switch (options)
                    {
                        case FileOptions.None:
                            break;
                        case FileOptions.Extract:
                            process.Execute("start /wait " + fullName + " x -o" + distDir + "\\ -y");
                            break;
                        case FileOptions.Select:
                            process.Execute("start explorer.exe /select, " + fullName.AddDoubleQuotes());
                            break;
                        default:
                            break;
                    }
                }
                catch (Exception ex)
                {
                    process.Echo(Messages.MSG_ERROR + ex.Message);
                    ex.Log("Wystąpił problem podczas pobierania pliku " + file);
                }
                finally
                {
                    System.Threading.Thread.Sleep(200);
                    if (delete)
                        process.Execute("del /F /Q \"" + fullName + "\"");

                    process.Echo(MSG_KONIEC_POBIERANIA);
                }
            }
            #region WinMerge
            public static string GetWinMergePath()
            {
                return OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.OperacjeNaPlikach.WinMerge);
            }
            public static string GetDefaultWinMergePath()
            {
                string str = "";
                try
                {
                    str = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Thingamahoochie\WinMerge", "Executable", "").AsString();
                    if (str.IsNull() || !File.Exists(str))
                        str = "";
                }
                catch { str = ""; }
                return str;
            }
            public static bool CanUseWinMerge()
            {
                string file = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.OperacjeNaPlikach.WinMerge);
                bool res = false;
                try
                {
                    if (file.IsNotNullOrWhiteSpace())
                    {
                        res = File.Exists(file);
                    }
                }
                catch { }
                return res;
            }
            public static void RunWinMerge(string file1, string file2)
            {
                List<string> l1 = new List<string>();
                l1.Add(file1);
                List<string> l2 = new List<string>();
                l2.Add(file2);
                RunWinMerge(l1, l2);
            }

            public static void RunWinMerge(List<string> list1, List<string> list2)
            {
                if (list1.Count == list2.Count)
                {
                    if (CanUseWinMerge())
                    {
                        string file1, file2;
                        List<string> nonexisting = new List<string>();
                        for (int i = 0; i < list1.Count; i++)
                        {
                            try
                            {
                                file1 = list1[i];
                                file2 = list2[i];
                                if (!File.Exists(file1))
                                {
                                    nonexisting.Add(file1);
                                    continue;
                                }
                                if (!File.Exists(file2))
                                {
                                    nonexisting.Add(file2);
                                    continue;
                                }
                                Process.Start(GetWinMergePath(), file1.AddDoubleQuotes() + " " + file2.AddDoubleQuotes());
                            }
                            catch (Exception ex)
                            {
                                ex.LogError();
                            }
                        }
                        if (nonexisting.Count == 1)
                        {
                            FormMain.Instance.ShowDxInfoDialog("Prak pliku: " + Constants.NewLineLinux + nonexisting[0]);
                        }
                        else if (nonexisting.Count > 1)
                        {
                            FormMain.Instance.ShowDxInfoDialog("Prak plików " + Constants.NewLineLinux + nonexisting.AsString(Constants.NewLineLinux));
                        }
                    }
                    else
                    {
                        FormMain.Instance.ShowDxErrorDialog("Nie znaleziono WinMerge.\nSprawdź opcje " + GlobalTools.GetOptionPath(Init.InitFormOptionNames.Work_Group.OperacjeNaPlikach.WinMerge));
                    }
                }
            }
            #endregion
            #region edytory
            private static Browser _EditorBrowser;
            private static Browser EditorBrowser
            {
                get
                {
                    if (_EditorBrowser == null)
                    {
                        _EditorBrowser = BrowserCache.GetBrowser(Init.InitFormBrowserNames.Setup.Edytory);
                    }
                    return _EditorBrowser;
                }
            }
            const string sysCommandPath = @"HKEY_CLASSES_ROOT\{0}\shell\open\command";
            const string userExtPath = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}";
            const string sysExtPath = @"HKEY_CLASSES_ROOT\{0}";
            const string sysOpenWithList = @"{0}\OpenWithProgIds";
            const string userOpenWithList = @"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithProgIds";
            const string userOpenWithList2 = @"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\OpenWithList";
            const string userDefProgramId = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{0}\UserChoice";

            public static string GetEditorForExtension(string ext)
            {
                string str = "";
                if (ext.IsNull())
                    ext = "*";

                if (!ext.StartsWith("."))
                    ext = "." + ext;

                string path = string.Format(userDefProgramId, ext);
                string docName = Registry.GetValue(path, "Progid", string.Empty).AsString();
                if (docName.IsNotNull())
                {
                    path = string.Format(sysCommandPath, docName);
                    docName = Registry.GetValue(path, string.Empty, string.Empty).AsString();
                    if (docName.IsNotNull())
                    {
                        docName = docName.GetFirstMatch("(.*\\.exe)", 1, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        if (docName.IsNotNull())
                            str = docName;
                    }
                }
                if (str.IsNull())
                {
                    path = string.Format(sysExtPath, ext);
                    docName = Registry.GetValue(path, string.Empty, string.Empty).AsString();
                    if (docName.IsNotNull())
                    {
                        str = GetExeForProgId(docName);
                    }
                }
                return str.TrimStartEnd('"');
            }
            private static string GetExeForProgId(string progId)
            {
                string path = string.Format(sysCommandPath, progId);
                string docName = Registry.GetValue(path, string.Empty, string.Empty).AsString();
                string str = "";
                if (docName.IsNotNull())
                {
                    docName = docName.GetFirstMatch("(.*\\.exe)", 1, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    if (docName.IsNotNull())
                        str = docName;
                }
                else
                {
                    if (!progId.XMatch("^Applications", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    {
                        progId = "Applications\\" + progId;
                        str = GetExeForProgId(progId);
                    }
                }
                return str.TrimStartEnd('"'); ;
            }
            public static EditorWithParams GetEditorForFile(EditorSource src, string file)
            {
                string ext = Path.GetExtension(file);
                return GetEditorForExtension(src, ext);
            }
            public static EditorWithParams GetEditorForExtension(EditorSource src, string ext)
            {
                EditorWithParams e = null;
                string typ = "";
                string opt = "";
                switch (src)
                {
                    case EditorSource.GUI:
                        break;
                    case EditorSource.JAVA:
                        break;
                    case EditorSource.OperacjeNaPlikach:
                        typ = "ONP";
                        opt = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Work_Group.OperacjeNaPlikach.TypEdytora);
                        break;
                    default:
                        break;
                }
                DataRow r;
                DataRow[] rows;
                string filter = "STP_ED_TYP = " + typ.EscapeSql();
                DataTable dt =  BrowserCache.GetBrowserData(Init.InitFormBrowserNames.Setup.Edytory);
                List<string> extensions = new List<string>();
                ext = ext.TrimStart('*','.');

                if (opt.Contains("R") && ext.IsNotNull())
                {
                    rows = dt.Select(filter + " AND STP_ED_EXT LIKE '%" + ext.PrepareString() + "%' AND STP_ED_EDYTOR IS NOT NULL");
                    e = GetEditor(rows, ext);
                    
                    if (e == null)
                    {
                        rows = dt.Select(filter + " AND STP_ED_EXT LIKE '%" + ext.PrepareString() + "%'");
                        e = GetEditor(rows, ext);
                    }
                }
                if (e == null)
                {
                    if (opt.Contains("G"))
                    {
                        r = dt.SelectFirstRow(filter + " AND STP_ED_EXT IS NULL AND STP_ED_EDYTOR IS NOT NULL");
                        if (r != null)
                        {
                            e = new EditorWithParams();
                            e.Editor = r["STP_ED_EDYTOR"].AsString();
                            e.Params = r["STP_ED_PARAMS"].AsString();
                        }
                    }
                    if (e == null)
                    {
                        if (opt.Contains("D"))
                        {
                           
                            if (ext.IsNotNull())
                            {
                                rows = dt.Select(filter + " AND STP_ED_EXT LIKE '%" + ext.PrepareString() + "%' AND STP_ED_EDYTOR IS NULL");
                                e = GetEditor(rows, ext);
                                if (e == null)
                                    e = new EditorWithParams();
                                
                                e.Editor = GetEditorForExtension(ext);
                            }
                        }
                    }
                }
                return e;
            }
            private static EditorWithParams GetEditor(DataRow[] rows, string ext)
            {
                List<string> extensions = new List<string>();
                if (rows.Length > 0)
                {
                    foreach (DataRow rr in rows)
                    {
                        extensions.Clear();
                        string[] parts = rr[""].AsString().Split(';');
                        foreach (string s in parts)
                        {
                            if (s.IsNotNull())
                                extensions.AddIfNotExist(s.Trim().TrimStart('*', '.'));
                        }

                        if (extensions.Contains(ext))
                        {
                            EditorWithParams e = new EditorWithParams();
                            e.Editor = rr["STP_ED_EDYTOR"].AsString();
                            e.Params = rr["STP_ED_PARAMS"].AsString();
                            return e;
                        }
                    }
                }
                return null;
            }
            #endregion
            #region otwieranie
            public static void OpenFiles(EditorSource src, params string[] files)
            {
                EditorWithParams ed = null;
                List<string> nonexisting = new List<string>();
                foreach (string file in files)
                {
                    try
                    {
                        if (!File.Exists(file))
                        {
                            nonexisting.Add(file);
                            continue;
                        }
                    }
                    catch
                    {
                        nonexisting.Add(file);
                        continue;
                    }

                    ed = GlobalTools.FilesTools.GetEditorForFile(src, file);
                    if (ed != null && ed.Editor.IsNull())
                    {
                        //string err = @"Nie mozna odnaleźć edytora Plik:" + file;
                        //err.LogWarning();
                    }
                    try
                    {
                        string program = (ed != null ? ed.Editor : "");
                        string parameters = (ed != null ? ed.Params : "");
                        if (program.IsNull())
                            program = file;
                        else
                            parameters += " " + file.AddDoubleQuotes();

                        Process.Start(program, parameters);
                    }
                    catch (Exception ex) { ex.LogError(); }
                }
                if (nonexisting.Count == 1)
                {
                    FormMain.Instance.ShowDxInfoDialog("Brak pliku: " + Constants.NewLineLinux + nonexisting[0]);
                }
                else if (nonexisting.Count > 1)
                {
                    FormMain.Instance.ShowDxInfoDialog("Brak plików " + Constants.NewLineLinux + nonexisting.AsString(Constants.NewLineLinux));
                }
            }
            
            public static Process OpenFile(EditorSource src, string file)
            {
                Process p = null;
                try
                {
                    EditorWithParams ed = null;
                    ed = GlobalTools.FilesTools.GetEditorForFile(src, file);
                    string program = (ed != null ? ed.Editor : "");
                    string parameters = (ed != null ? ed.Params : "");
                    if (program.IsNull())
                        program = file;
                    else
                        parameters += " " + file.AddDoubleQuotes();

                    p = Process.Start(program, parameters);
                }
                catch (Exception ex) { ex.LogError(); }
                return p;
            }

            #endregion
            public static void OpenExplorerAndSelect(string file)
            {
                Process.Start("explorer.exe", "/select, " + file.AddDoubleQuotes());
            }

            public static void OpenDirs(params string[] paths)
            {
                if (paths == null) 
                    return;
                List<string> nonexisting = new List<string>();
                foreach (string dirx in paths)
                {
                    string dir = dirx.TrimEnd('\\');
                    try
                    {
                        var info = File.GetAttributes(dirx);
                        if (info.Contains(FileAttributes.Directory))
                        {
                            if (!dir.EndsWith("\\"))
                                dir += "\\";
                        }
                        else
                        {
                            dir = Path.GetDirectoryName(dir);
                        }
                        
                        if (!Directory.Exists(dir))
                        {
                            nonexisting.Add(dir);
                            continue;
                        }
                    }
                    catch
                    {
                        nonexisting.Add(dir);
                        continue;
                    }
                    try
                    {
                        string parameters = "";
                        if (dir == dirx.TrimEnd('\\'))
                            parameters = dir.AddDoubleQuotes();
                        else
                            parameters = "/select, " + dirx.AddDoubleQuotes();
                        Process.Start("explorer.exe", parameters);
                    }
                    catch (Exception ex) { ex.LogError(); }
                }
                if (nonexisting.Count == 1)
                {
                    FormMain.Instance.ShowDxInfoDialog("Brak katalogu: " + Constants.NewLineLinux + nonexisting[0]);
                }
                else if (nonexisting.Count > 1)
                {
                    FormMain.Instance.ShowDxInfoDialog("Brak katalogów " + Constants.NewLineLinux + nonexisting.AsString(Constants.NewLineLinux));
                }
            }
        }
        #endregion
        
        #region Otis
        public static class OtisTools
        {
            public class AdditionalEffort
            {
                public decimal AddEffortSum
                {
                    get;
                    set;
                }
                public decimal RegularOverTime
                {
                    get;
                    set;
                }
                public decimal SupportSum
                {
                    get;
                    set;
                }
            }
            private const string Login = "http://intranet/index-service";
            private const string AdditionalPaymentUrl = "http://intranet/administration/supportAccount_single_init.action";
            private const string ReportUrl = "http://intranet/TMS_TABS/reports/account/peremployee/index.jsp";

            private static string GetLoginParams()
            {
                string login = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne_Group.Otis.OtisUser);
                string pass = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne_Group.Otis.OtisPass);

                string str = "login=" + login + "&password=" + pass + "&operation=check";
                return str;
            }

            public static AdditionalEffort GetAdditionalEffort(int rok, int miesiac)
            {
                ExtendedWebClient wc = GetWebClient();
                AdditionalEffort e = new AdditionalEffort();

                string str = "";
                str = wc.DownloadString(Login + "?" + GetLoginParams());
                string AdditionalPayment = "";
                try
                {
                    string par = "year=" + rok + "&month=" + miesiac + "&action:supportAccount_single_read=READ DATA";

                    AdditionalPayment = wc.DownloadString(AdditionalPaymentUrl + "?" + par);
                }
                catch { }
                
                if (AdditionalPayment.IsNotNull())
                {
                    string mask1 = "<tr>\\s*<td[^>]*>1(.*?)</td>\\s*<td[^>]*>(.*?)</td>\\s*</tr>";
                    string mask2 = "<tr>\\s*<td[^>]*>2(.*?)</td>\\s*<td[^>]*>(.*?)</td>\\s*</tr>";
                    string mask3 = "<tr>\\s*<td[^>]*>3(.*?)</td>\\s*<td[^>]*>(.*?)</td>\\s*</tr>";

                    string val1 = AdditionalPayment.GetFirstMatch(mask1, 2);
                    string val2 = AdditionalPayment.GetFirstMatch(mask2, 2);
                    string val3 = AdditionalPayment.GetFirstMatch(mask3, 2);
                    
                    e.AddEffortSum = val1.AsDecimal();
                    e.RegularOverTime = val2.AsDecimal();
                    e.SupportSum = val3.AsDecimal();
                }
                wc.Dispose();
                return e;
            }

            static bool isChecking = false;
            public static void SprawdzOtis(bool start)
            {
                if (isChecking==false)
                {
                    isChecking = true;
                    Thread otisThread = new Thread(new ParameterizedThreadStart(CheckOtis));
                    otisThread.Start(start);
                }
            }

            static void CheckOtis(object value)
            {
                try
                {
                    ExtendedWebClient w = GetWebClient();

                    string dateToday = DateTime.Today.ToString("yyyy-MM-dd");
                    string clock = "http://intranet/OUTER_TABS/detail/index_body.jsp?from=" + dateToday + "&to=" + dateToday;
                    
                    string login_frame = Login + "?" + GetLoginParams();
                    string data = "";
                    try
                    {
                        data = w.DownloadString(clock);
                    }
                    catch { }
                    if (data.IsNull() || data.IndexOf(dateToday) == -1)
                    {
                        try
                        {
                            string login = w.DownloadString(login_frame);
                            data = w.DownloadString(clock);
                        }
                        catch { }
                    }
                    string loginTime = "";
                    string brakeTime = "";

                    if (data.IsNotNull())
                    {
                        int idxStart = data.IndexOf(dateToday);
                        if (idxStart >= 0)
                        {
                            string dates = data.Substring(idxStart + dateToday.Length + 5);

                            string inMask = "<td [^>]*>\\s*(\\d\\d:\\d\\d)\\s*<span [^>]*>\\s*\\[in\\]\\s*</span>";
                            string outMask = "<td [^>]*>\\s*(\\d\\d:\\d\\d)\\s*<span [^>]*>\\s*\\[out\\]\\s*</span>";

                            List<string> listIn = dates.GetMatches(inMask, 1, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                            if (listIn.Count > 0)
                            {
                                List<string> listOut = dates.GetMatches(outMask, 1, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                long bTime = 0;
                                if (listIn.Count > 1)
                                {
                                    for (int i = 0; i < listIn.Count - 1; i++)
                                    {
                                        if (listOut.Count > i)
                                            bTime += GetSeconds(listIn[i + 1]) - GetSeconds(listOut[i]);
                                    }
                                }
                                brakeTime = GetTime(bTime);
                                loginTime = listIn[0];
                            }
                        }
                    }
                    try
                    {
                        data = w.DownloadString(ReportUrl);
                    }
                    catch { }
                    if (data.IsNull() || (data.IndexOf("Total balance") == -1 && data.IndexOf("Bilans godzin") == -1))
                    {
                        try
                        {
                            string login = w.DownloadString(login_frame);
                            data = w.DownloadString(ReportUrl);
                        }
                        catch { }
                    }
                    string bilans = "";
                    if (data.IsNotNull())
                    {
                        int idx = data.IndexOf("Total balance");
                        if (idx == -1)
                            idx = data.IndexOf("Bilans godzin");
                        if (idx > -1)
                        {
                            data = data.Substring(idx);
                            bilans = data.GetFirstMatch("(-?\\d+:\\d+)");
                        }
                    }

                    if (loginTime.XMatch("^0\\d:"))
                        loginTime = loginTime.Substring(1);

                    if (brakeTime.XMatch("^0\\d:"))
                        brakeTime = brakeTime.Substring(1);

                    if (loginTime.XMatch("^0\\d:"))
                        loginTime = loginTime.Substring(1);

                    FormMain.Instance.SetLoginTime(loginTime, brakeTime, bilans, value.AsBool());
                }
                finally
                {
                    try
                    {
                        isChecking = false;
                    }
                    catch { }
                }
            }
            static string TIME_MASK = "(\\d*):(\\d*):?(\\d*)";

            private static long GetSeconds(string time)
            {
                long h = time.GetFirstMatch(TIME_MASK, 1).AsInt();
                long m = time.GetFirstMatch(TIME_MASK, 2).AsInt();
                long s = time.GetFirstMatch(TIME_MASK, 3).AsInt();
                return s + m * 60 + h * 60 * 60;
            }
            private static string GetTime(long seconds)
            {
                long h = seconds / (60 * 60);
                long m = (seconds - (h * 60 * 60)) / 60;
                long s = (seconds - (h * 60 * 60) - (m * 60));
                return h.ToString() + ":" + (m > 9 ? "" : "0") + m.ToString() + ":" + (s > 9 ? "" : "0") + s.ToString();
            }

            static bool isGettingBilans = false;
            public static void GetBilans()
            {
                if (isGettingBilans)
                    return;
                isGettingBilans = true;
                Thread OtisBilansThread = new Thread(new ThreadStart(GetBilansData));
                OtisBilansThread.Start();
            }
            private static void GetBilansData()
            {
                try
                {
                    string data = "";
                    ExtendedWebClient w = GetWebClient();
                    string login_frame = Login + "?" + GetLoginParams();
                    
                    try
                    {
                        string login = w.DownloadString(login_frame);
                        data = w.DownloadString(ReportUrl);
                    }
                    catch { }
                    
                    string bilans = "";
                    if (data.IsNotNull())
                    {
                        int idx = data.IndexOf("Total balance");
                        if (idx == -1)
                            idx = data.IndexOf("Bilans godzin");
                        if (idx > -1)
                        {
                            data = data.Substring(idx);
                            bilans = data.GetFirstMatch("(-?\\d+:\\d+)");
                        }
                    }
                    if (bilans.IsNotNull())
                    {
                        if (FormMain.Instance != null && !FormMain.Instance.IsDisposed && !FormMain.Instance.Disposing)
                            FormMain.Instance.SetBilans(bilans);
                    }
                }
                finally
                {
                    try
                    {
                        isGettingBilans = false;
                    }
                    catch { }
                }
            }
        }
        #endregion

        #region SoftDev
        public class SoftDevTools
        {
            public static bool GetInfoFromSDForHistory
            {
                get
                {
                    return
                    OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Commit.AddInfoForHistory);
                }
            }
            public const string WEB_SOFT_DEV = "http://softdevtest:8081/SoftDev/View?ufi=";
            const string projMask = "<td [^>]*>\\s*Planned Ver\\.:\\s*</td>\\s*<td>\\s*<input .*?value=\"(.*?)\"";
            const string summaryMask = "<td [^>]*>\\s*Summary:?\\s*</td>\\s*<td>\\s*<textarea [^>]*>\\s*(.*?)</textarea>";
            static string CrMask = "(^(CR-)?(GENE-)?(\\d+\\w*))";
            
            public static void NawigateTo(string id)
            {
                if (id.IsNotNull())
                {
                    id = id.ToUpper();
                    Process[] sd = Process.GetProcessesByName("SoftDev");
                    if (sd != null && sd.Length == 1)
                    {
                        System.Threading.Thread.Sleep(50);
                        Clipboard.SetText(id);
                        User32.SetForegroundWindow(sd[0].MainWindowHandle);
                        Process softDev = sd[0];
                        System.Threading.Thread.Sleep(100);
                        softDev.BringWindowToFront();
                        if (User32.GetForegroundWindow() != softDev.MainWindowHandle)
                            User32.SwitchToThisWindow(softDev.MainWindowHandle, false);
                        if(User32.GetForegroundWindow() != softDev.MainWindowHandle)
                            User32.SwitchToThisWindow(softDev.MainWindowHandle, true);

                        if (User32.GetForegroundWindow() == softDev.MainWindowHandle)
                        {
                            WindowsInput.InputSimulator.SimulateKeyPress(WindowsInput.VirtualKeyCode.F6);
                            WindowsInput.InputSimulator.SimulateKeyPress(WindowsInput.VirtualKeyCode.EXECUTE);
                        }
                    }
                    else
                    {
                        FormMain.ShowErrorAlert("Nie można zidentyfikować SoftDev'a");
                    }
                }
            }
            
            public static bool GetCRInfo(bool onlyOne, bool historyCrs, bool getFromSD = true, bool getInfoFromSDForHistory = true)
            {
                HistoryCrs.Clear();
                Dictionary<string, string> historyList = new Dictionary<string, string>();
                List<string> history = TortoiseTools.GetHistoryLogMessages();
                string cr;
                
                string numCr;
                foreach (string s in history)
                {
                    cr = s.GetFirstMatch(CrMask);

                    if (cr.IsNotNull())
                    {
                        numCr = cr.GetFirstMatch(CrMask, 4);
                        if (!historyList.ContainsKey(numCr))
                            historyList.Add(numCr, s.Replace(cr, "").Trim());
                    }
                }
                WINDOW_INFO.AllCrs.Clear();
                if (getFromSD)
                {
                    Process[] sd = Process.GetProcessesByName("SoftDev");
                    if (sd != null && sd.Length == 1)
                    {
                        WINDOW_INFO.GetCr(sd[0].MainWindowHandle, onlyOne);
                    }
                    else
                    {
                        FormMain.ShowErrorAlert("Nie można zidentyfikować SoftDev'a");
                    }
                }
               
                foreach (WINDOW_INFO wi in WINDOW_INFO.AllCrs)
                {
                    if (historyList.ContainsKey(wi.Text))
                    {
                        wi.Log = historyList[wi.Text];
                        historyList.Remove(wi.Text);
                    }
                }
                if (!onlyOne)
                {
                    if (historyCrs)
                    {
                        int count = OptionCache.GetOptionValue(Init.InitFormOptionNames.Work_Group.Tortoise_Group.Commit.IloscCrowZHistorii).AsInt(8);
                        int i = 0;
                        try
                        {
                            foreach (KeyValuePair<string, string> kvp in historyList)
                            {
                                try
                                {
                                    if (i > 0 && i >= count)
                                        break;
                                    CRInfo ci = new CRInfo();
                                    ci.Log = kvp.Value;
                                    ci.Numer = kvp.Key;
                                    HistoryCrs.Add(ci);
                                    i++;
                                }
                                catch (Exception e)
                                {
                                    e.LogError("CR: " + kvp.Key);
                                }
                            }

                            int l = HistoryCrs.Count;
                            if (getInfoFromSDForHistory)
                            {
                                foreach (var c in HistoryCrs)
                                {
                                    var webRequest = WebRequest.Create(WEB_SOFT_DEV + GlobalTools.Options.CRPrefix + c.Numer);

                                    webRequest.GetReponseAsync(c).ContinueWith(ta =>
                                    {
                                        if (ta.Exception == null)
                                        {
                                            using (var sr = new StreamReader(ta.Result.GetResponseStream()))
                                            {
                                                string str = sr.ReadToEnd();
                                                if (ta.AsyncState is CRInfo)
                                                {
                                                    (ta.AsyncState as CRInfo).Projekt = str.GetFirstMatch(projMask);
                                                    (ta.AsyncState as CRInfo).Summary = str.GetFirstMatch(summaryMask);
                                                }
                                            }
                                        }
                                        else
                                            ta.Exception.LogError();
                                        l--;
                                    });
                                }
                                while (l > 0)
                                {
                                    //System.Threading.Thread.Sleep(10);
                                    Application.DoEvents();
                                }
                            }
                        }
                        catch (Exception ex) { ex.LogError(); }
                    }
                }

                return WINDOW_INFO.CR!=null;
            }
            public static void GetCRIngoFromWebSD(CRInfo c)
            {
                int l = 1;
                var webRequest = WebRequest.Create(WEB_SOFT_DEV + GlobalTools.Options.CRPrefix + c.Numer);
                webRequest.GetReponseAsync(c).ContinueWith(ta =>
                {
                    if (ta.Exception == null)
                    {
                        using (var sr = new StreamReader(ta.Result.GetResponseStream()))
                        {
                            string str = sr.ReadToEnd();
                            if (ta.AsyncState is CRInfo)
                            {
                                (ta.AsyncState as CRInfo).Projekt = str.GetFirstMatch(projMask);
                                (ta.AsyncState as CRInfo).Summary = str.GetFirstMatch(summaryMask);
                            }
                        }
                    }
                    else
                        ta.Exception.LogError();
                    l--;
                });
                while (l > 0)
                {
                    //System.Threading.Thread.Sleep(10);
                    Application.DoEvents();
                }
            }
            public static string CR
            {
                get
                {
                    if (WINDOW_INFO.CR != null)
                    {
                        return WINDOW_INFO.CR.Text;
                    }
                    return "";
                }
            }
            public static string Summary
            {
                get
                {
                    if (WINDOW_INFO.CR != null)
                    {
                        return WINDOW_INFO.CR.Summary;
                    }
                    return "";
                }
            }

            private class WINDOW_INFO
            {
                [DllImport("user32.dll", SetLastError = true)]
                static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);


                public static WINDOW_INFO CR
                {
                    get
                    {
                        if (AllCrs.Count > 0)
                            return AllCrs[0];
                        return null;
                    }
                }
                public static List<WINDOW_INFO> AllCrs = new List<WINDOW_INFO>();
                private static bool ContainsCr(string cr)
                {
                    foreach (WINDOW_INFO wi in AllCrs)
                        if (wi.Text == cr)
                            return true;
                    return false;
                }
                public WINDOW_INFO(IntPtr handle)
                {
                    Children = new List<WINDOW_INFO>();
                    Handle = handle;
                }

                public IntPtr Handle
                {
                    get;
                    set;
                }
                public string Text
                {
                    get;
                    set;
                }
                public string Projekt
                {
                    get
                    {
                        return GetCrDetails(7);
                    }
                }
                private string GetCrDetails(int num)
                {
                    if (!CanBeCR)
                        return string.Empty;
                    WINDOW_INFO w = CrDetails;
                    if (w != null && w.Children.Count > num)
                        return w.Children[num].Text;
                    return string.Empty;
                }
                public string Summary
                {
                    get
                    {
                        return GetCrDetails(15);
                    }
                }
                private WINDOW_INFO CrDetails
                {
                    get
                    {
                        WINDOW_INFO w = GetByName("Change Request", this.Children);
                        if (w != null)
                            return GetByName("Change Request Details", w.Children);
                        return null;
                    }
                }

                public List<WINDOW_INFO> Children
                {
                    get;
                    private set;
                }
                public bool CanBeCR
                {
                    get;
                    set;
                }
                public string ControlName
                {
                    get;
                    set;
                }
                public string Log
                {
                    get;
                    set;
                }
                public bool IsCr
                {
                    get
                    {
                        return CanBeCR &&
                            CrDetails != null;
                    }
                }
                public override string ToString()
                {
                    return "Text:" + Text + "; Child:" + Children.Count();
                }
                private static bool OnlyOne = false;
                public static void GetCr(IntPtr handle, bool onlyOne)
                {
                    OnlyOne = onlyOne;
                    AllCrs.Clear();
                    Skip.Clear();

                    GetWindows(handle, IntPtr.Zero);
                }
                private static bool GetWindows(IntPtr handle, IntPtr parent)
                {
                    if (CR != null && OnlyOne)
                        return false;
                    if (parent != IntPtr.Zero && parent != Win32.GetParent(handle))
                        return true;
                    WINDOW_INFO wi = new WINDOW_INFO(handle);
                    GetWindowInfo(wi);
                    if (wi.IsCr)
                    {
                        if (!ContainsCr(wi.Text))
                        {
                            AllCrs.Add(wi);
                        }
                        if (OnlyOne)
                            return false;
                        return true;
                    }
                    else
                    {
                        Win32.EnumChildWindows(handle, GetWindows, handle);
                    }
                    return true;
                }
                private static List<string> Skip = new List<string>();

                public static void GetWindowInfo(WINDOW_INFO info)
                {
                    int l = Win32.GetWindowTextLength(info.Handle);
                    StringBuilder text = new StringBuilder(l + 1);
                    Win32.GetWindowText(info.Handle, text, text.MaxCapacity);
                    string tx = text.ToString();
                    if (tx.IsNull())
                        tx = Win32.GetWindowText(info.Handle);
                    
                    
                    info.CanBeCR = tx.XMatch("^(CR-)?(GENE-)?\\d+((IT)|(SC))$");
                    if (info.CanBeCR)
                        tx = tx.XReplace("^(CR-)?(GENE-)?", "");
                    info.Text = tx;
                    if (info.CanBeCR && !ContainsCr(info.Text) && !Skip.Contains(tx))
                    {
                        IntPtr ChangeRequest = FindWindowEx(info.Handle, IntPtr.Zero, null, "Change Request");
                        if (ChangeRequest != IntPtr.Zero)
                        {
                            GetAllInfo(info);
                            Skip.Add(tx);
                        }
                    }
                }

                private static void GetAllInfo(WINDOW_INFO info)
                {
                    GCHandle h = GCHandle.Alloc(info);
                    Win32.EnumChildWindows(info.Handle, GetAllHildren, GCHandle.ToIntPtr(h));
                }

                private static bool GetAllHildren(IntPtr handle, IntPtr pointer)
                {
                    try
                    {
                        WINDOW_INFO hi = GCHandle.FromIntPtr(pointer).Target as WINDOW_INFO;
                        if (hi.Handle == Win32.GetParent(handle))
                        {
                            int l = Win32.GetWindowTextLength(handle);
                            StringBuilder text = new StringBuilder(l + 1);
                            Win32.GetWindowText(handle, text, text.MaxCapacity);

                            WINDOW_INFO wi = new WINDOW_INFO(handle);
                            string tx = text.ToString();
                            if (tx.IsNull())
                                tx = Win32.GetWindowText(wi.Handle);

                            wi.Text = tx;
                            hi.Children.Add(wi);
                            GetAllInfo(wi);
                        }
                    }
                    catch { }
                    return true;
                }
                private static WINDOW_INFO GetByName(string name, List<WINDOW_INFO> list)
                {
                    foreach (WINDOW_INFO wi in list)
                    {
                        if (wi.Text == name)
                            return wi;
                    }
                    return null;
                }
            }
            
            public class CRInfo
            {
                public string Numer
                {
                    get;
                    set;
                }
                public string Summary
                {
                    get;
                    set;
                }
                public string Projekt
                {
                    get;
                    set;
                }
                public string Log
                {
                    get;
                    set;
                }
                public bool SoftDev
                {
                    get;
                    set;
                }
            }
            public static List<CRInfo> HistoryCrs = new List<CRInfo>();

            public static List<CRInfo> AllCrs
            {
                get
                {
                    List<CRInfo> l = new List<CRInfo>();
                    
                    foreach (WINDOW_INFO wi in WINDOW_INFO.AllCrs)
                    {
                        l.Add(new CRInfo() { Numer = wi.Text, Summary = wi.Summary, Projekt = wi.Projekt, Log = wi.Log, SoftDev = true });
                    }
                    l.AddRange(HistoryCrs);
                    return l;
                }
            }


        }
        #endregion

        #region GridTools
        public static class GridTools
        {
            static GridTools()
            {
                AddedColor = Color.LightSkyBlue;
                ModifiedColor = Color.LightGreen;
                DisplayText = true;
                CustomColors = true;
            }

            public static Color AddedColor
            {
                get;
                set;
            }
            public static Color ModifiedColor
            {
                get;
                set;
            }
            public static bool DisplayText
            {
                get;
                set;
            }
            public static bool CustomColors
            {
                get;
                set;
            }

            public static void AddGridRowIndicatorEvent(GridControl grid)
            {
                foreach(var o in grid.ViewCollection)
                    if (o is GridView)
                        AddGridRowIndicatorEvent(o as GridView);
            }
            public static void AddGridRowIndicatorEvent(GridView view)
            {
                view.CustomDrawRowIndicator += new RowIndicatorCustomDrawEventHandler(view_CustomDrawRowIndicator);
                if (view.IndicatorWidth < 30)
                    view.IndicatorWidth = 30;
            }

            static void view_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
            {
                if (!e.Info.IsRowIndicator) return;
                if (!(CustomColors || DisplayText))
                    return;
                GridView gv = sender as GridView;
                if (gv != null)
                {
                    DataRow row = gv.GetDataRow(e.RowHandle);
                    string text = "";
                    if (row != null)
                    {
                        switch (row.RowState)
                        {
                            case DataRowState.Added:
                                e.Appearance.BackColor = AddedColor;
                                text = "N";
                                break;
                            case DataRowState.Modified:
                                if (row.IsRealyModified())
                                {
                                    e.Appearance.BackColor = ModifiedColor;
                                    text = "Z";
                                }
                                else
                                    return;
                                break;
                            default:
                                return;
                        }
                        if (CustomColors)
                        {
                            e.Appearance.DrawBackground(e.Cache, e.Bounds);

                            Rectangle r = e.Bounds;

                            e.Graphics.DrawRectangle(Pens.Brown, r);
                            if (e.Info.ImageIndex >= 0)
                            {
                                Image image = ((DevExpress.Utils.ImageCollection)e.Info.ImageCollection).Images[e.Info.ImageIndex];
                                r.Inflate(-4, -4);
                                e.Graphics.DrawImageUnscaled(image, r.Location);
                                r.Inflate(-6, 4);
                            }
                            if (DisplayText)
                            {
                                r.Inflate(-4, -4);
                                e.Graphics.DrawString(text, gv.GridControl.Font, Brushes.Black, r.Location);
                            }
                            e.Handled = true;
                        }
                        else if(DisplayText)
                        {
                            e.Info.DisplayText = text;
                        }
                    }
                }
            }
        }
        #endregion
    }
    public static class WebRequestExtensions
    {
        public static Task<WebResponse> GetReponseAsync(this WebRequest request, object state = null)
        {
            return Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, state);
        }
    }
    public class EditorWithParams
    {
        public string Editor
        {
            get;
            set;
        }
        public string Params
        {
            get;
            set;
        }
    }
    public enum EditorSource
    {
        GUI,
        JAVA,
        OperacjeNaPlikach
    }
    public class ExtendedWebClient : WebClient
    {
        public ExtendedWebClient()
        {
            Timeout = 10000;
            if(Proxy!=null)
                Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
            Credentials = CredentialCache.DefaultNetworkCredentials;
            UseDefaultCredentials = true;
        }
        public int Timeout
        {
            get;
            set;
        }
        public bool UseCashedCookies
        {
            get;
            set;
        }
        public bool SaveCookieHeader
        {
            get;
            set;
        }
        private WebResponse _Response;
        public WebResponse Response
        {
            get { return _Response; }
        }
        CookieContainer cookies = new CookieContainer();

        protected override WebRequest GetWebRequest(Uri address)
        {
            _Response = null;
            WebRequest request = base.GetWebRequest(address);
            if (request != null)
                request.Timeout = Timeout;

            if (request is System.Net.HttpWebRequest)
            {
                (request as System.Net.HttpWebRequest).ReadWriteTimeout = Timeout;
                (request as System.Net.HttpWebRequest).CookieContainer = cookies;
                if (UseCashedCookies)
                    (request as System.Net.HttpWebRequest).CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable);
            }
            return request;
        }

        protected override WebResponse GetWebResponse(WebRequest request)
        {
            _Response = base.GetWebResponse(request);
            if (SaveCookieHeader)
            {
                string s = _Response.Headers["Set-Cookie"];
                if (s.IsNotNull())
                    Headers.Add("Cookie", s);
            }
            return _Response;
        }

        public string DownloadPostString(string url, string parameters)
        {
            string str = this.UploadString(url, "POST", parameters);
            return str;
        }
    }
}

